Hey guys,--I met a weird problem about the float32 type in Go.This is my demo program: (You can run it via: http://play.golang.org/p/dn4V4TcFtr)package mainimport "fmt"func main() {compute(4.8)compute(4.7)compute(4.6)compute(4.5)}func compute(input float32) {result := int64(input * 100)fmt.Printf("Result is:%d\r\n", result)result = int64(int(input *10)*10)fmt.Printf("Result is:%d\r\n", result)}==================The output is:Result is:480 Result is:480 Result is:469 Result is:470 Result is:460 Result is:460 Result is:450 Result is:450You may notice that all the results are as expected except when input is 4.7I am confused about the float 4.7 * 100, why the result is 469?But if I let 4.7 * 10 first, then convert it to int type and multiply by 10 again, the result is 470, not 469.I don't know why, can anybody help to explain it? Thanks a lot!
You received this message because you are subscribed to the Google Groups "golang-dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-dev+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
package mainimport "fmt"func main() {compute(4.8)compute(4.7)compute(4.6)compute(4.5)}
func compute(input float32) {fmt.Println(input * 100)}
Thanks for your reply. It is caused by the precision of float32 type.Another question is how do I get 470, not 469 if I really have to let 4.7 * 100?
I mean is there a best practice to handle it?
x = float32(4.7) = 4.69999980926513671875x*100 = 469.999969482421875int(x*100) = 469int(x*100+0.5) = 470