-1

my code:

step := 10.0
precision := int(math.Log10(1/step))
fmt.PrintLn(precision)

I want precision == -1 but got 0...

1 Answer 1

2

Float to integer conversion truncates, so if your float number is e.g. 0.99, converting it to integer will be 0 and not 1.

If you want to round to an integer, you may simply use math.Round() (which returns float64 so you still need to manually convert to int, but the result will be what you expect):

step := 10.0
precision := int(math.Log10(1 / step))
fmt.Println(precision)

precision = int(math.Round(math.Log10(1 / step)))
fmt.Println(precision)

This will output (try it on the Go Playground):

0
-1

If you want to round to a specific fraction (and not to integer), see Golang Round to Nearest 0.05.

1
  • So cute you are, I just fix this problem lastnignt with same method, but I spend a long time to figure out the thought.
    – fdsafsdf
    Jan 10, 2021 at 4:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.