如何将包含美元金额的字符串转换为整数?

时间:2016-12-15 21:02:33

标签: ruby gsub

如何将包含"$39,900"形式的美元值的字符串转换为整数,以便用它进行计算?

我想我会尝试gsub,但这似乎不起作用:

str = "$39,900"
str.strip.gsub('$' '')
=> #<Enumerator: "$39,900":gsub("$")>

有人可以和我分享正确的方法吗?

5 个答案:

答案 0 :(得分:1)

#include <iostream> void Foo() { std::cout << "Foo" << std::endl; } void Bar() { std::cout << "Bar" << std::endl; } void FooBar(){ std::cout << "FooBar" << std::endl; } void Baz() { std::cout << "Baz" << std::endl; } void FooBaz(){ std::cout << "FooBaz" << std::endl; } int main() { void (*pFunc)(); void* pvArray[5] = {(void*)Foo, (void*)Bar, (void*)FooBar, (void*)Baz, (void*)FooBaz}; int choice; std::cout << "Which function: "; std::cin >> choice; std::cout << std::endl; // or random index: choice = rand() % 5; pFunc = (void(*)())pvArray[choice]; (*pFunc)(); // or iteratley call them all: std::cout << "calling functions iteraely:" << std::endl; for(int i(0); i < 5; i++) { pFunc = (void(*)())pvArray[i]; (*pFunc)(); } std::cout << std::endl; return 0; } - &gt; .gsub('$' '')(缺少逗号)

答案 1 :(得分:1)

SELECT product_id FROM sales WHERE status IN ('SENT', 'RECEIPT') GROUP BY product_id HAVING MIN(status) = 'RECEIPT' AND MAX(status) = 'SENT'; 应该有效

我在这里使用了import matplotlib.pyplot as plt plt.plot([1,2,3],[1,2,3],'ro') plt.axis([-4,4,-4,4]) plt.savefig('azul.png') plt.plot([0,1,2],[0,0,0],'ro') plt.axis([-4,4,-4,4]) plt.savefig('amarillo.png') 。如何运作最好在documentation

中解释

答案 2 :(得分:1)

正则表达式版本为:

str.gsub(/[^\d]/, '').to_i

[^\d]代表&#34;每个字符都不是数字&#34;。

答案 3 :(得分:1)

我使用:

str = "$39,900"
str.tr('^0-9', '').to_i # => 39900

以下是它如何分解:

str # => "$39,900"
.tr('^0-9', '') # => "39900"
.to_i # => 39900
'^0-9', ''中的

tr表示&#34;用''替换不是0..9的所有内容,只生成数字。

tr非常快,比gsub快得多,非常值得了解和使用此类问题。

如果坚持使用gsub使用正则表达式,则可以执行此操作:

str.gsub(/\D+/, '').to_i # => 39900

但我还是建议使用tr。这就是原因:

require 'fruity'

str = "$39,900"
compare do
  _gsub { str.gsub(/\D+/, '') }
  _tr { str.tr('^0-9', '') }
  jason_yost { str.scan(/\d/).join('') }
  nikita_mishain { str.tr('$,', '') }
  ruben_tf { str.gsub(/[^\d]/, '') }
end

# >> Running each test 8192 times. Test will take about 2 seconds.
# >> nikita_mishain is similar to _tr
# >> _tr is faster than ruben_tf by 4x ± 1.0
# >> ruben_tf is similar to _gsub
# >> _gsub is faster than jason_yost by 2x ± 0.1

答案 4 :(得分:0)

str = "$39,900"
str.scan(/\d/).join('').to_i
=> 39900

如果字符串不包含数字,则会返回0

str = "test"
str.scan(/\d/).join('').to_i
=> 0

这不会正确处理十进制。如果您需要获得浮点值,可以使用

str = '%.2f' % '$39,000.99'.delete( "$" ).delete(',')
str.to_f
=> 39000.99
相关问题