Python format float remove decimal

After looking over answers to several similar questions, this seems to be the best solution for me:

def floatToString(inputValue):
    return ('%.15f' % inputValue).rstrip('0').rstrip('.')

My reasoning:

%g doesn't get rid of scientific notation.

>>> '%g' % 0.000035
'3.5e-05'

15 decimal places seems to avoid strange behavior and has plenty of precision for my needs.

>>> ('%.15f' % 1.35).rstrip('0').rstrip('.')
'1.35'
>>> ('%.16f' % 1.35).rstrip('0').rstrip('.')
'1.3500000000000001'

I could have used format(inputValue, '.15f'). instead of '%.15f' % inputValue, but that is a bit slower (~30%).

I could have used Decimal(inputValue).normalize(), but this has a few issues as well. For one, it is A LOT slower (~11x). I also found that although it has pretty great precision, it still suffers from precision loss when using normalize().

>>> Decimal('0.21000000000000000000000000006').normalize()
Decimal('0.2100000000000000000000000001')
>>> Decimal('0.21000000000000000000000000006')
Decimal('0.21000000000000000000000000006')

Most importantly, I would still be converting to Decimal from a float which can make you end up with something other than the number you put in there. I think Decimal works best when the arithmetic stays in Decimal and the Decimal is initialized with a string.

>>> Decimal(1.35)
Decimal('1.350000000000000088817841970012523233890533447265625')
>>> Decimal('1.35')
Decimal('1.35')

I'm sure the precision issue of Decimal.normalize() can be adjusted to what is needed using context settings, but considering the already slow speed and not needing ridiculous precision and the fact that I'd still be converting from a float and losing precision anyway, I didn't think it was worth pursuing.

I'm not concerned with the possible "-0" result since -0.0 is a valid floating point number and it would probably be a rare occurrence anyway, but since you did mention you want to keep the string result as short as possible, you could always use an extra conditional at very little extra speed cost.

def floatToString(inputValue):
    result = ('%.15f' % inputValue).rstrip('0').rstrip('.')
    return '0' if result == '-0' else result

Remove trailing zeros from decimal in Python #

To remove trailing zeros from a decimal:

  1. Use the decimal.to_integral() method to check if the number has a fractional part.
  2. If it does, round the number and return it.
  3. If it does not, use the decimal.normalize() method to strip any trailing zeros.

Copied!

from decimal import Decimal num = Decimal('1.230000') # ✅ drop trailing zeros from decimal, using normalize() def remove_exponent(d): return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize() print(remove_exponent(num)) # 👉️ 1.23 # -------------------------------- # ✅ drop trailing zeros from decimal, using str.rstrip() num_2 = Decimal('1.230000') string = str(num_2) without_trailing_zeros = string.rstrip( '0').rstrip('.') if '.' in string else string result = Decimal(without_trailing_zeros) print(result) # 👉️ 1.23

The first function is taken from the Decimal FAQ section of the official docs.

The to_integral method rounds to the nearest integer.

Copied!

from decimal import Decimal # 👇️ True print(Decimal('1.0000') == Decimal('1.0000').to_integral()) # 👇️ False print(Decimal('1.9000') == Decimal('1.9000').to_integral()) print(Decimal('1.0000').to_integral()) # 👉️ 1

If the number has no decimal part, we use the quantize() method to round to a fixed number of decimal places.

If the number has a decimal part, we use the Decimal.normalize method to strip the rightmost trailing zeros.

Copied!

from decimal import Decimal print(Decimal('1.230000').normalize()) # 👉️ 1.23 print(Decimal('3.456000000').normalize()) # 👉️ 3.456

We only use the normalize() method if the number has a decimal part because it could remove zeros to the left of the decimal.

Copied!

from decimal import Decimal print(Decimal('500.000').normalize()) # 👉️ 5E+2 print(Decimal('510.100').normalize()) # 👉️ 510.1

Alternatively, you can use the str.rstrip() method.

To remove trailing zeros from a decimal:

  1. Use the str() class to convert the decimal to a string.
  2. Use the str.rstrip() method to strip the trailing zeros if the number has a decimal point.

Copied!

from decimal import Decimal num = Decimal('1.230000') string = str(num) without_trailing_zeros = string.rstrip( '0').rstrip('.') if '.' in string else string result = Decimal(without_trailing_zeros) print(result) # 👉️ 1.23

The first step is to convert the decimal to a string.

The str.rstrip method returns a copy of the string with the provided trailing characters removed.

We first strip trailing zeros, then try to strip the dot . if the decimal part only consisted of trailing zeros.

The example also checks whether the string contains a dot, so we don't attempt to strip trailing zeros from numbers that don't have a decimal part, e.g. 5000 to 5.

How do you print a float without a decimal in Python?

Use the int() class to get a number without the decimal places, e.g. result = int(my_float) . The int() class truncates floating-point numbers towards zero, so it will return an int that represents the number without the decimal places.

How do I remove float from decimal point?

format("%. 0f",xxz) + "%"); android.

How do you get rid of decimals in Python?

Type conversion in python helps to convert a decimal value number(floating number) to an integer. Thus converting float->int removes all decimals from a number.

What is .2f in Python?

As expected, the floating point number (1.9876) was rounded up to two decimal places – 1.99. So %. 2f means to round up to two decimal places. You can play around with the code to see what happens as you change the number in the formatter. ADVERTISEMENT.