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')
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.
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).
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.
You want to use %g
instead of %f
:
"%gx" % (factor / 100.00)
You can mix and match %g and %f like so:
"%g" % ("%.2f" % number)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With