Python convert int to string preserving zeros [duplicate] - python

This question already has answers here:
How do I pad a string with zeroes?
(19 answers)
Closed 6 years ago.
i'd like to convert a decimal to a string, where zeros at the end are preserved.
Using str method erases the last zeros.
Example:
number=0.20
Goal: "0.20"
e.g. using: str(number)="0.2" doesn't seem to work.

If you want 2 decimal places use:
number = 0.20
str_number = '%.2f' % number
Number before f indicates the desired number of places.

This can be done using string formatting.
"{0:.2f}".format(number)
Will return 0.20.
Doing your chosen method won't work because upon declaring number = 0.20 it omits the last zero right away. If you put that into your idle:
number = 0.20
number
0.2
So declaring number as str(number) is doing str(0.2).

Use the % operator with an appropriate format string:
'%1.2f' % number
=> '0.20'

Related

When rounding integer, don't add to the end [duplicate]

This question already has answers here:
How to implement conditional string formatting? [duplicate]
(3 answers)
Closed 1 year ago.
I currently am trying to work with a number that has variable decimal place lengths. It can either be an integer, or have up to 10 decimals i.e. 33.3333333. I wanted to restrict the number to only have 2 decimals when it exceeds the length, or maintain the original if it's less.
I've tried using "{:0:.2f}".format, but the problem is that for integers, it also adds .00 to the end of the string.
When I tried using round(3) it'll return 3.0.
Is there a method, preferably a single line, that can convert 3.333333 to 3.33 but still allow for 3 to stay as an int?
Try choosing the format as a function of the values wholeness:
"{d}" if int(a) == a else "{:0:.2f}"
Can you finish from there?
You can use a conditional expression to choose the format based on the type of the variable:
for x in (33.3333333, 3):
print(("{:0}" if isinstance(x, int) else "{:.2f}").format(x))
You could also implement it using a dictionary to map types to format strings:
formats = {int: "{:0}", float: "{:.2f}"}
for x in (33.3333333, 3):
print(formats.get(type(x)).format(x))

Force python to print a certain number of decimal places [duplicate]

This question already has answers here:
Python Decimals format
(6 answers)
Closed 3 years ago.
I have a python program which takes some floating type values and writes to a file.
I round these numbers to 6 decimal places and then convert to a string type before writing to file.
file.write(str(round(value,6)))
However with certain numbers the value written to file is in the format shown below.
e.g. 3e-06 or 4e-03
How can I avoid this and instead write out in decimal format like
0.000003 and 0.004000
How can I print exactly 6 figures after the decimal point.
You can use the f-string f'{value:.6f}'.
Example:
value = 0.234
print(f'{value:.6f}')
value = 1
print(f'{value:.6f}')
value = 0.95269175
print(f'{value:.6f}')
Output:
0.234000
1.000000
0.952692
Also, in the answer linked in a comment, there was reference to :g. That can work, but probably not in this situation, because g may print scientific notation where appropriate, and discards insignificant zeroes. Consider a slightly modified example using g:
value = 0.234
print(f'{value:.6g}')
value = 1
print(f'{value:.6g}')
value = 0.000000000095269175
print(f'{value:.6g}')
Output:
0.234
1
9.52692e-11
You can also use basic string formatting:
a = 3e-06
# Outputs 0.000003
print('%.6f' % a)
# Outputs 0.000003000000
print('%.12f' % a)

How to truncate a number with two positions after the decimal point in python? [duplicate]

This question already has answers here:
How to use Python string formatting to convert an integer representing cents to a float representing dollars?
(3 answers)
Limiting floats to two decimal points
(35 answers)
Closed 4 years ago.
I would like to truncate a number with only two positions after decimal point and return this number. But when I use the string format as float(" % .2f" % number), it returns 1.0 when the given number is like 1.0000. How could I resolve this problem? Thanks a lot.
It seems like my description was not clear enough. Let me take the 1.0005 as an example. I would like to return the number 1.00 with only two positions after the decimal point, rather than a string "1.00". So I choose to use string format to truncate the original number 1.0005 to a string "1.00" which satisfies the requirement of decimal points but it is still a string, I would like to return a number. So I use the float to convert it to a float number, but it seems like float() in gonna truncate the number to 1.0.

How to pad a string with leading zeros in Python 3 [duplicate]

This question already has answers here:
How do I pad a string with zeroes?
(19 answers)
Closed 3 years ago.
I'm trying to make length = 001 in Python 3 but whenever I try to print it out it truncates the value without the leading zeros (length = 1). How would I stop this happening without having to cast length to a string before printing it out?
Make use of the zfill() helper method to left-pad any string, integer or float with zeros; it's valid for both Python 2.x and Python 3.x.
It important to note that Python 2 is no longer supported.
Sample usage:
print(str(1).zfill(3))
# Expected output: 001
Description:
When applied to a value, zfill() returns a value left-padded with zeros when the length of the initial string value less than that of the applied width value, otherwise, the initial string value as is.
Syntax:
str(string).zfill(width)
# Where string represents a string, an integer or a float, and
# width, the desired length to left-pad.
Since python 3.6 you can use fstring :
>>> length = 1
>>> print(f'length = {length:03}')
length = 001
There are many ways to achieve this but the easiest way in Python 3.6+, in my opinion, is this:
print(f"{1:03}")
Python integers don't have an inherent length or number of significant digits. If you want them to print a specific way, you need to convert them to a string. There are several ways you can do so that let you specify things like padding characters and minimum lengths.
To pad with zeros to a minimum of three characters, try:
length = 1
print(format(length, '03'))
I suggest this ugly method but it works:
length = 1
lenghtafterpadding = 3
newlength = '0' * (lenghtafterpadding - len(str(length))) + str(length)
I came here to find a lighter solution than this one!

Python function for removing zeroes right of decimal, including decimal point? [duplicate]

This question already has answers here:
Most Pythonic way to print *at most* some number of decimal places [duplicate]
(3 answers)
Formatting floats without trailing zeros
(21 answers)
Closed 8 years ago.
I am using xlrd to read values from cells in an excel spreadsheet.
Whenever I detect a cell type = 2, then I know it is a number.
A number of 3 in cell will be returned as 3.0
And a number of 3.14 will be returned as 3.14
I will be converting numbers to text.
What function should I use to remove zeroes right of the decimal and the decimal?
The above 2 numbers should be 3 and 3.14
Use str.rstrip(), twice:
str_of_float.rstrip('0').rstrip('.')
This will remove trailing zeros, and if that leaves you with a trailing . it's removed as well.
Demo:
>>> '3.14'.rstrip('0').rstrip('.')
'3.14'
>>> '3.0'.rstrip('0').rstrip('.')
'3'
>>> '3000.0'.rstrip('0').rstrip('.')
'3000'
Don't be tempted to use .rstrip('.0'); it'll remove too many zeros:
>>> '3000.0'.rstrip('.0')
'3'
I always use format when printing values to strings. Using the format specs, it gives a good deal of control over what is printed.

Categories

Resources