DeeCoder
DeeCoder

Reputation: 86

Float formatting with decimals

I have a number charge.amount, whose value is 1900. I have a piece of ruby code like this:

charge.amount/100.to_f

The output is:

19.0

How do I display it with two decimal points like so:

19.00

Upvotes: 0

Views: 300

Answers (4)

DeeCoder
DeeCoder

Reputation: 86

The solution above works, but rounds the hundredth. Like so: 19.01 => 19.00

This works better to include hundredth of a cent:

sprintf('%.2f', charge.amount/100.to_f) 

Like so => 1901 => 19.01

Upvotes: 1

Thorin
Thorin

Reputation: 2034

You can use rails helper like:

number_with_precision(charge.amount/100, precision: 2) 

Upvotes: 0

dp7
dp7

Reputation: 6749

In Rails, you can use number_with_precision helper:

<%= number_with_precision(charge.amount/100, precision: 2) %>

Upvotes: 0

martincarlin87
martincarlin87

Reputation: 11062

Try this:

sprintf('%.2f', charge.amount/100)

Upvotes: 2

Related Questions