You can use the normalize method to remove extra precision.
>>> print decimal.Decimal('5.500')
5.500
>>> print decimal.Decimal('5.500').normalize()
5.5
To avoid stripping zeros to the left of the decimal point, you could do this:
def normalize_fraction(d):
normalized = d.normalize()
sign, digits, exponent = normalized.as_tuple()
if exponent > 0:
return decimal.Decimal((sign, digits + (0,) * exponent, 0))
else:
return normalized
Or more compactly, using quantize as suggested by user7116:
def normalize_fraction(d):
normalized = d.normalize()
sign, digit, exponent = normalized.as_tuple()
return normalized if exponent <= 0 else normalized.quantize(1)
You could also use to_integral() as shown here but I think using as_tuple this way is more self-documenting.
I tested these both against a few cases; please leave a comment if you find something that doesn't work.
>>> normalize_fraction(decimal.Decimal('55.5'))
Decimal('55.5')
>>> normalize_fraction(decimal.Decimal('55.500'))
Decimal('55.5')
>>> normalize_fraction(decimal.Decimal('55500'))
Decimal('55500')
>>> normalize_fraction(decimal.Decimal('555E2'))
Decimal('55500')
Answer from senderle on Stack OverflowYou can use the normalize method to remove extra precision.
>>> print decimal.Decimal('5.500')
5.500
>>> print decimal.Decimal('5.500').normalize()
5.5
To avoid stripping zeros to the left of the decimal point, you could do this:
def normalize_fraction(d):
normalized = d.normalize()
sign, digits, exponent = normalized.as_tuple()
if exponent > 0:
return decimal.Decimal((sign, digits + (0,) * exponent, 0))
else:
return normalized
Or more compactly, using quantize as suggested by user7116:
def normalize_fraction(d):
normalized = d.normalize()
sign, digit, exponent = normalized.as_tuple()
return normalized if exponent <= 0 else normalized.quantize(1)
You could also use to_integral() as shown here but I think using as_tuple this way is more self-documenting.
I tested these both against a few cases; please leave a comment if you find something that doesn't work.
>>> normalize_fraction(decimal.Decimal('55.5'))
Decimal('55.5')
>>> normalize_fraction(decimal.Decimal('55.500'))
Decimal('55.5')
>>> normalize_fraction(decimal.Decimal('55500'))
Decimal('55500')
>>> normalize_fraction(decimal.Decimal('555E2'))
Decimal('55500')
Answer from the Decimal FAQ in the documentation:
>>> def remove_exponent(d):
... return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
>>> remove_exponent(Decimal('5.00'))
Decimal('5')
>>> remove_exponent(Decimal('5.500'))
Decimal('5.5')
>>> remove_exponent(Decimal('5E+3'))
Decimal('5000')
Hello everyone,
I am still new to python and learning.
So I practiced some exercises and made an app that calculates the percentage from the number the user enters.
My question use, how can I terminate the .0 part if the user enters an Int and keep the decimal part if they enter a float?
so for example, 5% of 100 is 5 ( Int)
and 5.1% of 100 is 5.1 (float)
I have a float formatted to 2 decimal places. I need to eliminate the 2nd decimal place if it's a "0" but still keep 2 decimal places open for when its 2 whole numbers.
number = float(25.20458)
print(format(number, ".2f"))
#Comes out as 25.20
#Need 25.2Windows 10 and Python 3.7
import math
result=int(math.floor(85.21))
print(result)
Then you should consider casting to int which does the same thing but without the trailing .0 instead of math.floor:
>>> int(85.21)
85
I want to save the number as a file name
Since OP will not be working with negative numbers, they could keep this, or use int(math.floor(...)) that works also for negative numbers.
If want convert integers and floats numbers to strings with no trailing 0 use this with map or apply:
df = pd.DataFrame({'col1':[1.00, 1, 0.5, 1.50]})
df['new'] = df['col1'].map('{0:g}'.format)
#alternative solution
#df['new'] = df['col1'].apply('{0:g}'.format)
print (df)
col1 new
0 1.0 1
1 1.0 1
2 0.5 0.5
3 1.5 1.5
print (df['new'].apply(type))
0 <class 'str'>
1 <class 'str'>
2 <class 'str'>
3 <class 'str'>
Name: new, dtype: object
I think something like this should work:
if val.is_integer() == True :
val = int(val)
elif val.is_float() == True :
val = Decimal(val).normalize()
Assuming that val is a float value inside the dataframe's column. You simply cast the value to be integer.
For float value instead you cut extra zeros.
You would need to reassign x to the value of x = int(x) or you could also use str.format if you just want the output formatted:
print "Het antwoord van de berekening is: {:.0f}.".format(x)
int and round will exhibit different behaviour, if you have anything >= 5 after the decimal point then int will floor but round will round up, if you want to actually use round you might want to combine the two:
In [7]: x = round(1.5)
In [8]: x
Out[8]: 2.0
In [9]: int(x)
Out[9]: 2
Or again combine with str.format:
In [10]: print "Het antwoord van de berekening is: {:.0f}".format(round(1.5))
Het antwoord van de berekening is: 2
The round() function cannot alter the x variable in place, as numbers are immutable. Instead, the rounded result is returned, which your code ignores.
Store the result back in x:
x = round(x)
This will give you a floating point number rounded to the nearest whole number.
Alternatively, use x = int(x), which gives you an integer number, but floors that number (removes the decimal portion regardless if it is closer to the next whole number or not).
Here's a function to format your numbers the way you want them:
def formatNumber(num):
if num % 1 == 0:
return int(num)
else:
return num
For example:
formatNumber(3.11111)
returns
3.11111
formatNumber(3.0)
returns
3
you can use string formatting
>>> "%g" % 1.1
'1.1'
>>> "%g" % 1.0
'1'
You could just remove the '.' between the digits:
s = '0.0.1'
s = s.replace('.', '')
after that you can make it an int:
int(s)
By making it an integer, you will also remove any leading zeros. If you need a string afterwards just convert it back to string:
s = str(int(s))
You could use join and a comprehension:
>>> s = '0.0.1'
>>> ''.join(c for c in s if c != '.')
'001'
If you want to strip the leading 0s:
>>> str(int(''.join(c for c in s if c != '.')))
'1'