What about converting it to int?
>>>int(a)
100
Just for the sake of completeness, there are many many ways to remove the decimal part from a string representation of a decimal number, one that I can come up right now is:
s='100.0'
s=s[:s.index('.')]
s
>>>'100'
Perhaps there's another one more simple.
Hope this helps!
Answer from Paulo Bu on Stack OverflowWhat about converting it to int?
>>>int(a)
100
Just for the sake of completeness, there are many many ways to remove the decimal part from a string representation of a decimal number, one that I can come up right now is:
s='100.0'
s=s[:s.index('.')]
s
>>>'100'
Perhaps there's another one more simple.
Hope this helps!
If you do not want to convert it to an int you can also split it.
>>> a = 100.25
>>> str(a).split('.')[0]
>>> '100' # result is now a string
I need to remove decimals from float to get 6 characters after the dot WITHOUT rounding For example I have 0.00655379 and I need to get 0.006553
Videos
I am looking to manipulate a data frame of floats which all need 6 decimal points after manipulation.
I am looking to add brackets and () around the floats based on conditionals which is why I need to convert to strings. I then can concat the two strings together
However when I convert to str, it reduces the number of decimals to 2.
For example
-35.920000 Original Dataframe
Converted to str
-35.92 After conversion
If I convert the string back to a float, it does not retain the 6 decimals from the original df.
My understanding is both values are stored the same and they both are logically = when checked in the notebook , but for management reasons I am trying to see if there is a way to coerce the string method the take a literal copy of the float, rather than reducing it down.
Sorry for the formatting, I am on mobile .
Thanks
Using %f format specifier:
('%.2f' % (value,)).rstrip('0').rstrip('.')
Using round() function:
str(round(value)).rstrip('0').rstrip('.')
Use round together with %g -- you want at most 2 digits shown, so round to two digits, then use %g to print it as short as possible:
>>> "%g" % round(20.016, 2)
'20.02'
>>> "%g" % round(20, 2)
'20'
See PEP 3101:
'g' - General format. This prints the number as a fixed-point
number, unless the number is too large, in which case
it switches to 'e' exponent notation.
Old style (not preferred):
>>> "%g" % float(10)
'10'
New style:
>>> '{0:g}'.format(float(21))
'21'
New style 3.6+:
>>> f'{float(21):g}'
'21'
rstrip doesn't do what you want it to do, it strips any of the characters you give it and not a suffix:
>>> '30000.0'.rstrip('.0')
'3'
Actually, just '%g' % i will do what you want.
EDIT: as Robert pointed out in his comment this won't work for large numbers since it uses the default precision of %g which is 6 significant digits.
Since str(i) uses 12 significant digits, I think this will work:
>>> numbers = [ 0.0, 1.0, 0.1, 123456.7 ]
>>> ['%.12g' % n for n in numbers]
['1', '0', '0.1', '123456.7']
For pandas >= 1.0:
<NA> type was introduced for 'Int64'. You can now do this:
df['your_column'].astype('Int64').astype('str')
And it will properly convert 1.0 to 1.
Alternative:
If you do not want to change the display options of all pandas, @maxymoo solution does, you can use apply:
df['your_column'].apply(lambda x: f'{x:.0f}')
Converting to int (i.e. with .astype(int).astype(str)) won't work if your column contains nulls; it's often a better idea to use string formatting to explicitly specify the format of your string column; (you can set this in pd.options):
>>> pd.options.display.float_format = '{:,.0f}'.format
>>> df.astype(float).sum()
0 7
1 4
2 11
dtype: float64
With Python < 3 (e.g. 2.6 [see comments] or 2.7), there are two ways to do so.
# Option one
older_method_string = "%.9f" % numvar
# Option two
newer_method_string = "{:.9f}".format(numvar)
But note that for Python versions above 3 (e.g. 3.2 or 3.3), option two is preferred.
For more information on option two, I suggest this link on string formatting from the Python documentation.
And for more information on option one, this link will suffice and has info on the various flags.
Python 3.6 (officially released in December of 2016), added the f string literal, see more information here, which extends the str.format method (use of curly braces such that f"{numvar:.9f}" solves the original problem), that is,
# Option 3 (versions 3.6 and higher)
newest_method_string = f"{numvar:.9f}"
solves the problem. Check out @Or-Duan's answer for more info, but this method is fast.
Python 3.6
Just to make it clear, you can use f-string formatting. This has almost the same syntax as the format method, but make it a bit nicer.
Example:
print(f'{numvar:.9f}')
More reading about the new f string:
- What's new in Python 3.6 (same link as above)
- PEP official documentation
- Python official documentation
- Really good blog post - talks about performance too
Here is a diagram of the execution times of the various tested methods (from last link above):

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'
I tried
n1=input('First number')
n2=input('Second number')
sum = float(n1) + float(n2)
str(sum)
print('The sum of the values is: ' + sum)My error is:
TypeError: can only concatenate str (not "float") to str
I tried googling this error and got some answers like print(f' which I didn't really understand, and some others that looked a little complicated, I am very new.
I am trying to improve my googling skills.
Unfortunately it seems that not even the new-style formatting with float.__format__ supports this. The default formatting of floats is the same as with repr; and with f flag there are 6 fractional digits by default:
>>> format(0.0000000005, 'f')
'0.000000'
However there is a hack to get the desired result - not the fastest one, but relatively simple:
- first the float is converted to a string using
str()orrepr() - then a new
Decimalinstance is created from that string. Decimal.__format__supportsfflag which gives the desired result, and, unlikefloats it prints the actual precision instead of default precision.
Thus we can make a simple utility function float_to_str:
import decimal
# create a new context for this task
ctx = decimal.Context()
# 20 digits should be enough for everyone :D
ctx.prec = 20
def float_to_str(f):
"""
Convert the given float to a string,
without resorting to scientific notation
"""
d1 = ctx.create_decimal(repr(f))
return format(d1, 'f')
Care must be taken to not use the global decimal context, so a new context is constructed for this function. This is the fastest way; another way would be to use decimal.local_context but it would be slower, creating a new thread-local context and a context manager for each conversion.
This function now returns the string with all possible digits from mantissa, rounded to the shortest equivalent representation:
>>> float_to_str(0.1)
'0.1'
>>> float_to_str(0.00000005)
'0.00000005'
>>> float_to_str(420000000000000000.0)
'420000000000000000'
>>> float_to_str(0.000000000123123123123123123123)
'0.00000000012312312312312313'
The last result is rounded at the last digit
As @Karin noted, float_to_str(420000000000000000.0) does not strictly match the format expected; it returns 420000000000000000 without trailing .0.
If you are satisfied with the precision in scientific notation, then could we just take a simple string manipulation approach? Maybe it's not terribly clever, but it seems to work (passes all of the use cases you've presented), and I think it's fairly understandable:
def float_to_str(f):
float_string = repr(f)
if 'e' in float_string: # detect scientific notation
digits, exp = float_string.split('e')
digits = digits.replace('.', '').replace('-', '')
exp = int(exp)
zero_padding = '0' * (abs(int(exp)) - 1) # minus 1 for decimal point in the sci notation
sign = '-' if f < 0 else ''
if exp > 0:
float_string = '{}{}{}.0'.format(sign, digits, zero_padding)
else:
float_string = '{}0.{}{}'.format(sign, zero_padding, digits)
return float_string
n = 0.000000054321654321
assert(float_to_str(n) == '0.000000054321654321')
n = 0.00000005
assert(float_to_str(n) == '0.00000005')
n = 420000000000000000.0
assert(float_to_str(n) == '420000000000000000.0')
n = 4.5678e-5
assert(float_to_str(n) == '0.000045678')
n = 1.1
assert(float_to_str(n) == '1.1')
n = -4.5678e-5
assert(float_to_str(n) == '-0.000045678')
Performance:
I was worried this approach may be too slow, so I ran timeit and compared with the OP's solution of decimal contexts. It appears the string manipulation is actually quite a bit faster. Edit: It appears to only be much faster in Python 2. In Python 3, the results were similar, but with the decimal approach slightly faster.
Result:
Python 2: using
ctx.create_decimal():2.43655490875Python 2: using string manipulation:
0.305557966232Python 3: using
ctx.create_decimal():0.19519368198234588Python 3: using string manipulation:
0.2661344590014778
Here is the timing code:
from timeit import timeit
CODE_TO_TIME = '''
float_to_str(0.000000054321654321)
float_to_str(0.00000005)
float_to_str(420000000000000000.0)
float_to_str(4.5678e-5)
float_to_str(1.1)
float_to_str(-0.000045678)
'''
SETUP_1 = '''
import decimal
# create a new context for this task
ctx = decimal.Context()
# 20 digits should be enough for everyone :D
ctx.prec = 20
def float_to_str(f):
"""
Convert the given float to a string,
without resorting to scientific notation
"""
d1 = ctx.create_decimal(repr(f))
return format(d1, 'f')
'''
SETUP_2 = '''
def float_to_str(f):
float_string = repr(f)
if 'e' in float_string: # detect scientific notation
digits, exp = float_string.split('e')
digits = digits.replace('.', '').replace('-', '')
exp = int(exp)
zero_padding = '0' * (abs(int(exp)) - 1) # minus 1 for decimal point in the sci notation
sign = '-' if f < 0 else ''
if exp > 0:
float_string = '{}{}{}.0'.format(sign, digits, zero_padding)
else:
float_string = '{}0.{}{}'.format(sign, zero_padding, digits)
return float_string
'''
print(timeit(CODE_TO_TIME, setup=SETUP_1, number=10000))
print(timeit(CODE_TO_TIME, setup=SETUP_2, number=10000))