Ruby - 将字符串转换为浮点数返回 0.0

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15136127/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:47:42  来源:igfitidea点击:

Ruby - conversion string to float return 0.0

rubystringfloating-pointtype-conversion

提问by user984621

In a variable is stored this value: $10.00And I need to get this 10.00

在一个变量中存储了这个值:$10.00我需要得到这个10.00

I've tried to convert this value to float:

我试图将此值转换为浮点数:

new_price = '%.2f' % (price.to_f)

but I get just 0.0.

但我得到了0.0

What's wrong with that? I've tried also

那有什么问题?我也试过

price = price.strip
price[0]=""
new_price = '%.2f' % (price.to_f)

But even this didn't help me... where is a problem?

但即使这对我也没有帮助......哪里有问题?

Thanks

谢谢

回答by froderik

You need to remove the $first. The whole thing like this:

您需要删除第$一个。整个事情是这样的:

'%.2f' % '.00'.delete( "$" ).to_f

or

或者

'%.2f' % '.00'[1..-1].to_f

if you like density and may encounter non dollars.

如果你喜欢密度,可能会遇到非美元。

回答by Odysseus Ithaca

To set it in a variable:

要将其设置在变量中:

 current_price= '%.2f' % '.00'.delete( "$" ).to_f

The more common error, is a value in the thousands where there's a comma in the string like: 10,000.00. The comma will cause the same truncation error, but the decimal won't, and many programmers won't even catch it (we don't even notice the comma anymore). To fix that:

更常见的错误是字符串中有逗号的千位值,例如:10,000.00。逗号会导致同样的截断错误,但小数不会,许多程序员甚至不会抓住它(我们甚至不再注意到逗号)。要解决这个问题:

current_price= '%.2f' % '10,000.00'.delete( "," ).to_f

回答by Jexoteric

Adding on to froderick's answer of:

添加到 froderick 的回答:

You need to remove the $ first. The whole thing like this:

您需要先删除 $ 。整个事情是这样的:

'%.2f' % '.00'.delete( "$" ).to_f

or

或者

'%.2f' % '.00'[1..-1].to_f

if you like density and may encounter non dollars. you need to format the code for output to ensure that you get two decimal places >with

如果你喜欢密度,可能会遇到非美元。你需要格式化输出的代码以确保你得到两个小数位 >with

You need to format your output string to ensure you get two decimal places.

您需要格式化输出字符串以确保获得两位小数。

puts "Current amount: #{format("%.2f", amount)}"