Last active
February 24, 2023 21:26
-
-
Save HarlemSquirrel/1d72133516aa51826c2b5a38aec15cf8 to your computer and use it in GitHub Desktop.
Ruby float and decimal math
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## | |
# Run this with different versions of Ruby and BigDecimal to see different results. | |
# | |
# https://ruby-doc.org/3.2.1/exts/bigdecimal/BigDecimal.html | |
# | |
require "bigdecimal/util" | |
result_float_math = ((111.87 - 99) * 2) | |
puts "= Ruby v#{RUBY_VERSION}" | |
puts "= BigDecimal v#{BigDecimal::VERSION}" | |
puts "= Float::DIG #{Float::DIG}" | |
puts "== Basic conversion" | |
float = -8.37 | |
decimal = float.to_d | |
puts "#{float.class} #{float}" | |
puts "#{decimal.class} #{decimal}" | |
puts "== Math" | |
puts "((111.87 - 99) * 2) => #{result_float_math.class} #{result_float_math}" | |
result_float_math_dec = result_float_math.to_d | |
puts "((111.87 - 99) * 2).to_d => #{result_float_math_dec.class} #{result_float_math_dec}" | |
result_dec_math = ((111.87 - 99).to_d * 2) | |
puts "((111.87 - 99).to_d * 2) => #{result_dec_math.class} #{result_dec_math}" |
Author
HarlemSquirrel
commented
Feb 24, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment