views:

727

answers:

2

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')
+3  A: 

You want to use %g instead of %f:

"%gx" % (factor / 100.00)
Naaff
awesome. works well in my scenario. Unfortunately though it seems that "%.3gx" doesn't work as I'd expect. the 3 is total digits, not maximum digits after the decimal point. That means 2.12345 will be 2.12 but 22.12345 will be 22.1 instead of 22.12. Luckily in my scenario it doesn't matter, but do you know a way around that?
bjeanes
Formatting with %g will give either the 'natural' representation of the number (without trailing zeros) or the scientific representation (whichever is shorter, basically). %.3g, as you pointed out, sets the total number of digits to 3 rather than setting the number of digits after the decimal point. If you want to control the number of digits after the decimal point you need to use %f, as %.3f specifies 3 digits after the decimal point (padding with 0, if necessary). Unfortunately, I don't know of a way to mix and match these two alternatives.
Naaff
A: 

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
Joelio