-1

my code:

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

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

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
fdsafsdf
  • 19
  • 4

1 Answers1

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.

icza
  • 389,944
  • 63
  • 907
  • 827
  • 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 '21 at 04:09