ruby 在ruby中将字符串转换为十进制数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9956766/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert string to decimal number in ruby
提问by ElektroStudios
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
# :(
回答by Sergio Tulentsev
回答by Tau-fan Ar-if
If you want more accurate answer with the calculation to avoid bug like this https://www.codecademy.com/en/forum_questions/50fe886f68fc44056f00626cyou can use conversion to decimal example :
如果您想通过计算获得更准确的答案以避免像https://www.codecademy.com/en/forum_questions/50fe886f68fc44056f00626c这样的错误,您可以使用转换为十进制示例:
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
这应该会使打印的数字变为十进制,但是如果您想再次将其设置为浮点数,只需再次将其放入 to_f
size=size.to_f
puts size
回答by lucianosousa
You also can use the decimal class for it
您也可以使用小数类
a = '2.45'
Decimal(a) # => 2.45
UPDATE:
更新:
Use bigdecimal as @bigtex777 mentioned:
使用 bigdecimal 作为@bigtex777 提到:
source: http://ruby-doc.org/stdlib-2.2.2/libdoc/bigdecimal/rdoc/BigDecimal.html
来源:http: //ruby-doc.org/stdlib-2.2.2/libdoc/bigdecimal/rdoc/BigDecimal.html
回答by MegaTux
Capitalized conversion methods are a well-established Ruby idiom. See this great post from Advi Grimm
大写转换方法是一个完善的 Ruby 习语。请参阅 Advi Grimm 的这篇精彩帖子
Integer("641339524823408659")
=> 641339524823408659

