How to Format a String with Floats in Ruby Using #{Variable}

How to format a string with floats in Ruby using #{variable}?

Use round:

"Current amount: #{amount.round(2)}"

How can I format a float to a certain number of decimal and integer digits?

You can use sprintf('%05.2f', value).

The key is that the format is width . precision, where width indicates a minimum width for the entire number, not just the integer portion.

def print_float(value)
sprintf('%05.2f', value)
end
print_float(1)
# => "01.00"
print_float(2.4)
# => "02.40"
print_float(1.4455)
# => "01.45"

Floating-point format sequences in Ruby

The %n.mf format means the entire output field width is n character positions, and the number of places shown after the decimal point is m, with blank padding in front of the number if necessary to complete the entire field with of n. The decimal is padded right with 0s if needed to bring the number of visible decimal places up to m.

So the value 23.12 with a format of %8.3f will show as bb23.120 (where each b is a blank, not really a b). A format of %8.1f would yield bbbb23.1. A format of %8.0f would give bbbbbb23.

Note that if the formatted number would be more characters than the requested entire field width, then the field will just be made bigger to accommodate the number, so it's not truncated. In the above example, a format of %3.2f for 23.12 would give 23.12.

For the %3.2f case, the field width is given as 3 with 2 digits after the decimal point. Since 2 decimal places plus the decimal point already consume 3 character positions, any float printed with this format will be printed in their entirety with no preceding blanks. You'd get the same result with %2.2f or %1.2f or %0.2f. However this format will always give 2 decimal places either truncating or zero-padding if needed to make it exactly 2 visible digits.

Saving a number with specific decimal places to a variable

The method number_with_precision is a helper method for views only, and it returns a string version of the number. It doesn't return a number with the specified precision, if that's what you're looking for. The good news is, if you want exactly what number_with_precision gives you, you can use sprintf.

sprintf('%.2f', 3.1415926)    # result: "3.14"

sprintf returns a value you can store, instead of printing to stdout like printf does. So you can easily capture it:

number = sprintf('%.2f', 3.1415926)

If you wanted to treat it as a number, you could probably build a class that does this for you, and converts to and from a Float as needed.

How to convert a float 0.0 into a return string of 0?

This should suit your needs to convert floating integers to normal integers:

def convert_number(n)
n == n.to_i ? n.to_i : n
end

convert_number(0.0)
=> 0
convert_number(1.5)
=> 1.5

If you need to make the additional conversion to a string, simply wrap the body of convert_number in parens and call to_s:

def convert_number_to_s(n)
(n == n.to_i ? n.to_i : n).to_s
end

convert_number_to_s(1.5)
=> "1.5"
convert_number_to_s(2.0)
=> "2"

Dynamic formatting

You should try:

"%.#{5}f" % var_name

with variables:

var_name = 0.00001
num = 5

"%.#{num}f" % var_name
# => "0.00001"

num = 6
"%.#{num}f" % var_name
# => "0.000010"

How to round a very small floating point number with trailing zeros?

you can set the number of digits to be shown:

p "%0.08f" % x # => "0.00009263"

Format integer to string with fixed length in Ruby

How about getting the last three digits using % 1000 instead of doing string manipulations?

[1, 12, 123, 1234].map { |e| format('%03d', e % 1000) }

Update:

As suggested by the Tin Man in the comments, the original version is better in terms of readability and only abount 1.05x slower than this one, so in most cases it probably makes sense to use that.

Float with 'unnecessary' digits

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'


Related Topics



Leave a reply



Submit