英文:
Find decimal count from shopspring decimal library
问题
我正在使用golang中的github.com/shopspring/decimal来进行与十进制相关的操作,而不是使用浮点数来实现实际精度。
我有一个要求,需要找到十进制库值的小数位数。
例如:
price := decimal.NewFromFloat(0.00355)
fmt.Println("Price:", price) // Price:0.00355
这是我使用十进制的方式。现在我想要计算相同十进制数的小数位数。
在上面的示例中,小数位数为5
,因为有五个小数点。
查看了文档,但没有找到正确的操作。有人可以帮忙吗?提前感谢。
英文:
I am using github.com/shopspring/decimal for decimal related operations in golang instead of float for actual precision.
I have a requirement to find the decimal count for a decimal library value.
eg:-
price := decimal.NewFromFloat(0.00355)
fmt.Println("Price:", price) // Price:0.00355
This is how I use the decimal. So now I want to count the number of decimals from the same decimal.
In the above example the decimal count would be 5
since there are five decimal points.
Checked the docs but couldn't find the right operation for this. Can somebody help with this?
Thanks in advance.
答案1
得分: 1
你可以将十进制值转换为字符串,然后计算小数点后的字符数。
0.00355 => "0.00355" => count=5
英文:
You can convert decimal value to string, then count number of char after point .
.
0.00355 => "0.00355" => count=5
答案2
得分: 1
你可以使用decimal.Exponent()
方法,并询问数字的标度(scale)是多少。
package main
import (
"fmt"
"github.com/shopspring/decimal"
)
func main() {
x := decimal.NewFromFloat(123.456789)
s := x.Exponent()
fmt.Printf("十进制值 %v 的标度(scale)为 %v\n", x, s)
}
这将输出:
十进制值 123.456789 的标度(scale)为 -6
英文:
Wouldn't you just use decimal.Exponent()
and ask the number what its scale is?
https://goplay.tools/snippet/9Y6BP1dcOuA
package main
import (
"fmt"
"github.com/shopspring/decimal"
)
func main() {
x := decimal.NewFromFloat(123.456789)
s := x.Exponent()
fmt.Printf("decimal value %v has a scale of %v\n", x, s)
}
Which yields
>
> decimal value 123.456789 has a scale of -6
>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论