Why is BigDecimal returning a weird value?

前端 未结 6 620
花落未央
花落未央 2021-01-04 02:59

I am writing code that will deal with currencies, charges, etc. I am going to use the BigDecimal class for math and storage, but we ran into something weird with it.

6条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-04 03:56

    On Mac OS X, I'm running ruby 1.8.7 (2008-08-11 patchlevel 72) [i686-darwin9]

    irb(main):004:0> 1876.8 == BigDecimal('1876.8') => true
    

    However, being Ruby, I think you should think in terms of messages sent to objects. What does this return to you:

    BigDecimal('1876.8') == 1876.8
    

    The two aren't equivalent, and if you're trying to use BigDecimal's ability to determine precise decimal equality, it should be the receiver of the message asking about the equality.

    For the same reason I don't think formatting the BigDecimal by sending a format message to the format string is the right approach either.

提交回复
热议问题