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

17,894

Solution 1

You want to use %g instead of %f:

"%gx" % (factor / 100.00)

Solution 2

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

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

Solution 3

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.

Solution 4

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

Solution 5

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
Share:
17,894
Bo Jeanes
Author by

Bo Jeanes

Updated on July 16, 2022

Comments

  • Bo Jeanes
    Bo Jeanes almost 2 years

    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.

    • 1.20 -> 1.2x
    • 1.78 -> 1.78x
    • 0.80 -> 0.8x
    • 2.00 -> 2x

    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')