Arithmetic in ruby

后端 未结 6 1432
日久生厌
日久生厌 2020-12-16 06:25

Why this code 7.30 - 7.20 in ruby returns 0.0999999999999996, not 0.10?

But if i\'ll write 7.30 - 7.16, for examp

6条回答
  •  情书的邮戳
    2020-12-16 07:05

    The problem is that floating point is inaccurate. You can solve it by using Rational, BigDecimal or just plain integers (for example if you want to store money you can store the number of cents as an int instead of the number of dollars as a float).

    BigDecimal can accurately store any number that has a finite number of digits in base 10 and rounds numbers that don't (so three thirds aren't one whole).

    Rational can accurately store any rational number and can't store irrational numbers at all.

提交回复
热议问题