Convert string to decimal number in ruby

旧城冷巷雨未停 提交于 2019-12-03 10:24:39

问题


I need to work with decimals. In my program, the user need to put a number with decimals to convert that number.

The problem is: If I try to convert the argument into a number I get a integer without decimals.

# ARGV[0] is: 44.33

size = ARGV[0]

puts size.to_i
# size is: 44
# :(

回答1:


You call to_i, you get integer.

Try calling to_f, you should get a float.

For more string conversion methods, look here.




回答2:


If you want more accurate answer with the calculation to avoid bug like this https://www.codecademy.com/en/forum_questions/50fe886f68fc44056f00626c you can use conversion to decimal example :

require 'bigdecimal'
require 'bigdecimal/util'

size = ARGV[0]
size = size.to_d

this should make the printed number become decimal but if you want to make it as float again just put this to_f again

size=size.to_f

puts size



回答3:


You also can use the decimal class for it

a = '2.45'
Decimal(a) # => 2.45

UPDATE:

Use bigdecimal as @bigtex777 mentioned:

source: http://ruby-doc.org/stdlib-2.2.2/libdoc/bigdecimal/rdoc/BigDecimal.html




回答4:


Capitalized conversion methods are a well-established Ruby idiom. See this great post from Advi Grimm

Integer("641339524823408659")
=> 641339524823408659


来源:https://stackoverflow.com/questions/9956766/convert-string-to-decimal-number-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!