Bo Jeanes
Bo Jeanes

Reputation: 6383

Only show decimal point if floating point component is not .00 sprintf/printf

I am pretty formatting a floating point number but want it to appear as an integer if there is no relevant floating point number.

I.e.

I can achieve this with a bit of regex but wondering if there is a sprintf-only way of doing this?

I am doing it rather lazily in ruby like so:

("%0.2fx" % (factor / 100.0)).gsub(/\.?0+x$/,'x')

Upvotes: 45

Views: 19675

Answers (8)

Viktor
Viktor

Reputation: 3090

If you're using rails, you can use rails' NumberHelper methods: http://api.rubyonrails.org/classes/ActionView/Helpers/NumberHelper.html

number_with_precision(13.001, precision: 2, strip_insignificant_zeros: true)
# => 13
number_with_precision(13.005, precision: 2, strip_insignificant_zeros: true)
# => 13.01

Be careful, because precision means all digits after decimal point in this case.

Upvotes: 29

Yarin
Yarin

Reputation: 183779

Easy with Rails: http://api.rubyonrails.org/classes/ActionView/Helpers/NumberHelper.html#method-i-number_with_precision

number_with_precision(value, precision: 2, significant: false, strip_insignificant_zeros: true)

Upvotes: 2

Ivan Carrasco Quiroz
Ivan Carrasco Quiroz

Reputation: 605

I was looking for a function to truncate (not approximate) a float or decimal number in Ruby on Rails, I figure out the follow solution to do that:

you guys can try in your console, the example:

>> a=8.88
>> (Integer(a*10))*0.10
>> 8.8

I hope it helps somebody. :-)

Upvotes: -2

Eugene
Eugene

Reputation: 1013

I ended up with

price = price.round(precision)
price = price % 1 == 0 ? price.to_i : price.to_f

this way you even get numbers instead of strings

Upvotes: 6

alexebird
alexebird

Reputation: 63

Here's another way:

decimal_precision = 2
"%.#{x.truncate.to_s.size + decimal_precision}g" % x

Or as a nice one-liner:

"%.#{x.truncate.to_s.size + 2}g" % x

Upvotes: 3

gylaz
gylaz

Reputation: 13581

You can mix and match %g and %f like so:

"%g" % ("%.2f" % number)

Upvotes: 30

Joelio
Joelio

Reputation: 4691

I just came across this, the fix above didnt work, but I came up with this, which works for me:

def format_data(data_element)
    # if the number is an in, dont show trailing zeros
    if data_element.to_i == data_element
         return "%i" % data_element
    else
    # otherwise show 2 decimals
        return "%.2f" % data_element
    end
end

Upvotes: 3

Naaff
Naaff

Reputation: 9333

You want to use %g instead of %f:

"%gx" % (factor / 100.00)

Upvotes: 51

Related Questions