Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

  • 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') 
like image 670
Bo Jeanes Avatar asked May 08 '09 03:05

Bo Jeanes


People also ask

How do you get the decimal part of a float?

Using the modulo ( % ) operator The % operator is an arithmetic operator that calculates and returns the remainder after the division of two numbers. If a number is divided by 1, the remainder will be the fractional part. So, using the modulo operator will give the fractional part of a float.

How do you print a float with no decimal places?

printf("%. 0f\n", my_float); This will tell printf to include 0 decimal places of precision (you can, of course, use other values as well).

How do I get rid of .00 in Python?

Using int() method To remove the decimal from a number, we can use the int() method in Python. The int() method takes the number as an argument and returns the integer by removing the decimal part from it. It can be also used with negative numbers.


2 Answers

You want to use %g instead of %f:

"%gx" % (factor / 100.00) 
like image 151
Naaff Avatar answered Oct 05 '22 15:10

Naaff


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

"%g" % ("%.2f" % number) 
like image 30
gylaz Avatar answered Oct 05 '22 17:10

gylaz