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

标签 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

请帮忙。

最佳答案

那个总和是正确的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/

相关文章:

ruby - 通过 cURL POST 请求向 Sinatra 发送 JSON

android - Rhodes:无法检测到 NDK 工具链路径(损坏的 NDK 安装?)

ruby - Hanami,显示 'post' Controller / View

javascript - Rails - 动态更改表单中的选项

ruby - 在一个区 block 内产生什么意思?

sql - PostgreSQL 条件 where 子句

ruby-on-rails - 如何在 Rails 中引入模块

ruby - 将自定义条目添加到 Cocoapods 生成的 acknowledgments.plist 中

ruby - gem 安装 memcached 失败

ruby-on-rails - 在 Rails 5 中迭代 JSON 数组