How do I convert "$ 10.80" to decimal? By using regex?
7 Answers
It's maybe not the best way to do it but here is something that works :
"$ 10.80".match(/[0-9|\.]+/)[0].to_f
1 Comment
TonyTakeshi
Nice solution. Could just use this to extract the decimal value from any string. Thanks
s = "$ 10.80"
BigDecimal.new s.match(/(\d+\.\d+)/)[1]
Returns your value as an BigDecimal to preserve precision.
1 Comment
d11wtq
Why not use BigDecimal if you want to preserve precision?
If you know that it always has $ at the beginning, then just remove that, and a simple to_f will do.
"$ 10.00"[1..-1].to_f
1 Comment
Tyler K
This. Why would you complicate the problem any more than necessary?