我编写了一个计算器:
require 'bigdecimal'
def addition()
print "Enter the first number "
number1 = BigDecimal(gets.chomp)
print "Enter the second number "
number2 = BigDecimal(gets.chomp)
sum = number1 + number2
print sum
end
它没有给出正确的总和。如果我输入 4.21
作为第一个,2.11
作为第二个,我得到 0.632E1
。如果我输入 4.21
作为第一个,2.11
作为第二个,我得到 0.632E1
。
请帮忙。
最佳答案
那个总和是正确的。 0.632E1
是 6.32 的符号。
要获得看起来更“正常”的数字:
# BigDecimal built-in conversion to String
sum.to_s('F')
如BigDecimal documentation for .to_s所示
您还可以使用:
# Converts to Float, you would lose precision for display, but at least you get
# the normal expected behaviour of a Float
sum.to_f
# Converts to String with known precision (technically this just goes via Float)
sprintf( '%.4f', sum )
关于ruby - 为什么我的 BigDecimal 计算器输出的值不正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24838324/