Leo Leo - 3 months ago 9
Ruby Question

Float with 'unnecessary' digits

I need to make a number out of the string. to do that i use well known maneuver looking something like this:

Float(string_var) rescue nil


This works nicely, however I do have a tiny, little problem. If a string is
"2.50"
, variable I get is
2.5
. Is it even possible to create Float object with 'unnecessary' 0 digit at the end? can I literally translate
"2.50"
into
2.50
?

Answer

In short, the answer is no, given the question, as any Float, when examined, will use Float's to_s function, eliciting an answer without trailing zeroes.

Float will always give you a numeric value that can be interpreted any way you wish, though. In your example, you will get a float value (given a string that is a parsable float). What you are asking then, is how to display that value with trailing zeroes. To do that, you will be turning the float value back into a string.

Easiest way to accomplish that is to use the format given by one of your respondents, namely

string_var = "2.50"
float_value = Float(string_var) rescue nil # 2.5
with_trailing_zeroes = "%0.2f" % float_value # '2.50'