Problem converting from int to float

前端 未结 6 1827
[愿得一人]
[愿得一人] 2021-01-02 00:27

There is a strange behavior I cannot understand. Agreed that float point number are approximations, so even operations that are obviously returning a number without decimal

6条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-02 00:53

    I can't answer why the second one works and the first one doesn't. However, I can tell you that 195.95 is a non-terminating decimal in binary, and as such round off errors like this one are bound to happen.

    Try converting to a double rather than float. You could also use a money or a decimal type rather than a float. That will store the number differently and more accurately.

    For more on floating point numbers and the IEEE representation, go here:

    http://en.wikipedia.org/wiki/IEEE_754

提交回复
热议问题