本文介绍了美元为“钱”的Ruby字符串转换为数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前有没有一种宝石可以为此目的而用美元兑换所有字符串并将其转换为数字?例如:

Is there currently a gem that's capable of taking strings, all in USD for this purpose, and converting them to a number? Some examples would be:


  • $ 7,600将变为7600

  • 5500将变为进入5500

我知道在 5500示例中我只能执行 5500 .to_i,但是导入的电子表格不是 t一致,其中一些包含逗号和美元符号,而另一些则不包含。

I know on the "5500" example I can just do "5500".to_i, but the spreadsheets being imported aren't consistent and some include commas and dollar signs while others do not. There a decent way of handling this across the board in Ruby?

我尝试过类似 money_string.scan(/ \d /)这样的方法吗? .join 似乎很好,只是担心我会遇到我还没有发现的极端情况,例如小数位。

I've tried something like money_string.scan(/\d/).join which seems to be fine, just worried I'll run into edge cases I haven't found yet, such as decimal places.

推荐答案

为什么在调用 .to_i

示例:

"$7,600".gsub(/\D/,'').to_i

对于浮点数:

"$7,600.90".gsub(/[^\d\.]/, '').to_f

这篇关于美元为“钱”的Ruby字符串转换为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 09:56