4 ms·
BigDecimal("123.45") != 123.45.to_d. You should always prefer the former. In the latter, 123.45 is first read as a float, which introduces an error because it i
by edflsafoiewq 6y ago
BigDecimal("123.45") != 123.45.to_d. You should always prefer the former. In the latter, 123.45 is first read as a float, which introduces an error because it is not exactly representable as a float.
- pqdbr 6y agoRuby 2.7.2, just fire up irb: BigDecimal("123.45") == 123.45.to_d => true
- edflsafoiewq 6y agoShows you what I know. I thought I had tested this. I guess it keeps only a certain amount of precision.
- gioele 6y agoThat is just a coincidence (decimal ending in "5"), plus the fact that `.to_d` does some cleanup preprocessing. Counterexample: BigDecimal("1.5999999999999996") == 1.5999999999999996.to_d => false The most ergonomic way to initialize decimal numbers is IMO "123.45".to_d (Note the quotes around the number. `.to_d` is being called on a string.) BigDecimal's only lossless API is through strings. It would be nice to have native support for decimals at the parser level: 0d123.45 => BigDecimal("123.45")