为什么我的BigDecimal计算器输出的值不正确?

时间:2014-07-19 08:23:58

标签: ruby

我编写了一个计算器:

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

请帮忙。

1 个答案:

答案 0 :(得分:4)

该总和正确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 )