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.
CodePudding user response:
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
CodePudding user response:
You can convert decimal value to string, then count number of char after point .
.
0.00355 => "0.00355" => count=5