Nathan
Nathan

Reputation:

Ruby string to_f... bug?

"9.99".to_f
=> 999.0

Is this the expected behavior? How would one convert "9.99" to 9.99

Upvotes: 4

Views: 1526

Answers (5)

Sergey Mirvoda
Sergey Mirvoda

Reputation: 3239

Sure. It's a culture dependent conversion. Tested on IronRuby 0.9

Upvotes: -1

Mladen Jablanović
Mladen Jablanović

Reputation: 44080

Maybe some nasty gem or a Rails plugin changed your String#to_f behaviour...

Upvotes: 1

ezpz
ezpz

Reputation: 12037

What version? This works as expected on 1.8.7.

irb(main):001:0> "9.99".to_f
=> 9.99

.

ruby -e "puts \"9.99\".to_f"
9.99

Upvotes: 1

Reuben Mallaby
Reuben Mallaby

Reputation: 5767

What version of Ruby are you using ?

"9.99".to_f results in 9.99 for me using Ruby 1.8.6 on Windows.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500385

What locale are you running in? My guess is that it's treating "." as a thousands separator (which happens to be in the wrong place in this case) and "," as a decimal point.

Try

"9,99".to_f

... but if that works, it's probably dependent on the current culture of the system, and you should look to find a culture-invariant way of converting.

Upvotes: 3

Related Questions