3

How do I convert "$ 10.80" to decimal? By using regex?

1
  • What do you mean by "decimal"? An arbitrary precision floating-point? Commented Dec 18, 2011 at 10:13

7 Answers 7

6

It's maybe not the best way to do it but here is something that works :

"$ 10.80".match(/[0-9|\.]+/)[0].to_f
Sign up to request clarification or add additional context in comments.

1 Comment

Nice solution. Could just use this to extract the decimal value from any string. Thanks
6
s = "$ 10.80"
BigDecimal.new s.match(/(\d+\.\d+)/)[1]

Returns your value as an BigDecimal to preserve precision.

1 Comment

Why not use BigDecimal if you want to preserve precision?
4

There are already several solutions, but I'd like to add

>> "$ 10.80"[/[\d\.]+/].to_f #=> 10.8

Comments

3

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

This. Why would you complicate the problem any more than necessary?
2

Code that may be easier to understand for regex illiterates:

"$ 10.80".split(' ')[1].to_f

Comments

1

This soluiton matches any floating point number (including eg "$ .89") and preserves precision:

require 'bigdecimal'

s = "$ 10.80"

puts BigDecimal.new(s.match(/\d*\.?\d+/)[0]).to_s('F')  # 10.8

Comments

0

you can even use split method.

"$ 10.80".split(' ')[1].to_f

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.