Comma as decimal point in python - python

I am new to python.
In python, I wish to convert float variables to string variable with 2 decimal places and decimal comma.
For example, 3.1415 --> 3,14
it works fine. But when I convert 1.20, it gives 1,2 instead of 1,20.
I want the latter one
Is there an easy way to achieve that? Thank You Guys
My code is in the following:
s=float(input())
a=round(s,2)
x=str(a)
y=x.replace('.',','))
print(y)

Try using this:
>>> num = 1.201020
>>> '{:.2f}'.format(num).replace('.', ',')
'1,20'

Related

How to represent the number like '1.108779411784206406864790428E-69', between 0-1 in Python

I have a number that comes from Sigmoid function like '1.108779411784206406864790428E-69' but it's naturally should be between 0-1. How can I represent it in that way? Thanks
The number that you got is the scientific notation of this number: 0.0000000000000000000000000000000000000000000000000000000000000000000011087794117842064068647904281594
To get the number like that, you need to do this:
x = 1.108779411784206406864790428E-69
print("%.100f" % x)
"%.100f" is the string to format, where 100 is the number of floats you need to show.
You can use the format statement to print. The original value is a float. For the convenience of readability python prints in scientific notation since this is a very small number. You can print upto more decimal places.. I have printed upto 96 decimal places below.
>>> a=1.108779411784206406864790428E-69
>>> "{:.96f}".format(a)
'0.000000000000000000000000000000000000000000000000000000000000000000001108779411784206406864790428'
Hope this helps.

ValueError when converting string received from Micro:bit radio into integer in Python [duplicate]

I have a string in the format: 'nn.nnnnn' in Python, and I'd like to convert it to an integer.
Direct conversion fails:
>>> s = '23.45678'
>>> i = int(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '23.45678'
I can convert it to a decimal by using:
>>> from decimal import *
>>> d = Decimal(s)
>>> print d
23.45678
I could also split on '.', then subtract the decimal from zero, then add that to the whole number ... yuck.
But I'd prefer to have it as an int, without unnecessary type conversions or maneuvering.
How about this?
>>> s = '23.45678'
>>> int(float(s))
23
Or...
>>> int(Decimal(s))
23
Or...
>>> int(s.split('.')[0])
23
I doubt it's going to get much simpler than that, I'm afraid. Just accept it and move on.
What sort of rounding behavior do you want? Do you 2.67 to turn into 3, or 2. If you want to use rounding, try this:
s = '234.67'
i = int(round(float(s)))
Otherwise, just do:
s = '234.67'
i = int(float(s))
>>> s = '23.45678'
>>> int(float(s))
23
>>> int(round(float(s)))
23
>>> s = '23.54678'
>>> int(float(s))
23
>>> int(round(float(s)))
24
You don't specify if you want rounding or not...
You could use:
s = '23.245678'
i = int(float(s))
"Convert" only makes sense when you change from one data type to another without loss of fidelity. The number represented by the string is a float and will lose precision upon being forced into an int.
You want to round instead, probably (I hope that the numbers don't represent currency because then rounding gets a whole lot more complicated).
round(float('23.45678'))
The expression int(float(s)) mentioned by others is the best if you want to truncate the value. If you want rounding, using int(round(float(s)) if the round algorithm matches what you want (see the round documentation), otherwise you should use Decimal and one if its rounding algorithms.
round(float("123.789"))
will give you an integer value, but a float type. With Python's duck typing, however, the actual type is usually not very relevant. This will also round the value, which you might not want. Replace 'round' with 'int' and you'll have it just truncated and an actual int. Like this:
int(float("123.789"))
But, again, actual 'type' is usually not that important.
I believe this is a useless bug that should be corrected in Python.
int('2') --> 2 That converts the string '2' into an the integer 2.
int(2.7) --> 2 Converts a float to an int.
int('2.7') SHOULD convert to 2. This is how Perl works, for example. Yes, this does two things at once. It converts the string and when it finds it is in a representation that is a float, it should convert to int.
Otherwise, why insist that float('2') should work? It is an integer string, because there is no decimal point. So it has to convert from string which is an integer, directly to float.
I don't know but perhaps someone can answer whether the python interpreter, if the required int(float(x)) is used, if it actually goes through the process of first converting to float and then converting to int. That would make this bug even more critical to correct.

How to round numbers

How would I be able to round numbers like these to two decimal places which are all stored in a variable which has been outputted by a web scraper:
4.7532
4.7294
4.7056
4.6822857142857
4.65868
4.63522
4.6119866666667
4.58898
4.566064
4.543216
I am new to python so i'm not sure. I'm using Python 2
Use the built-in function round(), example:
>>> round(4.7532,2)
4.75
>>> round(4.7294,2)
4.73
I think from what you say, you have a single string containing these numbers, and you want to print them out as 2dp formatted?
If so, the first thing to do is split the single string into an array, and convert to floating point numbers
numstr = """4.7532
4.7294
4.7056
4.6822857142857"""
nums = [float(x) for x in numstr.split("\n")]
This gives us an array of floating point python numbers
Now, we want to output them, having rounded. We can do that a few ways, the easiest is probably
for num in nums:
print "%0.2f" % num
That will loop over all your numbers, and print them out one per line, formatted to two decimal places

How to properly use string formatting in Python 2.7?

Ok, please bear with me, I'm completely new to this. This is for school, and the exact syntax isn't important here for my assignment, but for my own personal knowledge I want to know a little more about string formatting.
whenever I use %f it defaults to 2 decimal places. Is there a string format that I can use on a float that will show the float with the number of decimals it actually has?
for instance my list contains 2.0, 2.01, 2.001, 2.0001 and I want to use a string format to print them as they look. Which format code would I use or how could I use %f properly if possible?
This is in Python 2.7 on Windows 7(if that matters).
%g may be what you're looking for:
>>> "%g, %g, %g, %g" % (2.1, 2.01, 2.001, 2.0001)
'2.1, 2.01, 2.001, 2.0001'
If you convert the float to a string, then when you print it, it will be displayed just as you wrote it.
>>> x = str(2.0)
>>> print(x)
2.0
>>> x = str(2.01)
>>> print(x)
2.01
>>> x = str(2.001)
>>> print(x)
2.001
>>> x = str(2.0001)
>>> print(x)
2.0001
(In fact, to be precise, in Python you're not actually converting the floating point object, but creating a string object that looks like it. But that's a bit outside of the scope of your question.)
UPDATE
Someone posted a way to remove trailing zeros from floating point numbers using the Decimal class, here: Removing Trailing Zeros in Python

Add zeros to a float after the decimal point in Python

I am reading in data from a file, modify it and write it to another file. The new file will be read by another program and therefore it is crucial to carry over the exact formatting
for example, one of the numbers on my input file is:
1.000000
my script applies some math to the columns and should return
2.000000
But what is currently returned is
2.0
How would I write a float for example my_float = 2.0, as my_float = 2.00000 to a file?
Format it to 6 decimal places:
format(value, '.6f')
Demo:
>>> format(2.0, '.6f')
'2.000000'
The format() function turns values to strings following the formatting instructions given.
From Python 3.6 it's also possible to do f-string formatting. This looks like:
f"{value:.6f}"
Example:
> print(f"{2.0:.6f}")
'2.000000'
I've tried n ways but nothing worked that way I was wanting in, at last, this worked for me.
foo = 56
print (format(foo, '.1f'))
print (format(foo, '.2f'))
print (format(foo, '.3f'))
print (format(foo, '.5f'))
output:
56.0
56.00
56.000
56.00000
Meaning that the 2nd argument of format takes the decimal places you'd have to go up to. Keep in mind that format returns string.
I've had problems with using variables in f strings. When all else fails, read the manual :)
"A consequence of sharing the same syntax as regular string literals is that characters in the replacement fields must not conflict with the quoting used in the outer formatted string literal."
https://docs.python.org/3/reference/lexical_analysis.html#f-strings
Case in point:
my_number = 90000
zeros = '.2f'
my_string = f"{my_number:,{zeros}}"
print (my_string)
90,000.00
my_string = f'{my_number:,{zeros}}'
will not work, because of the single quotes.
Quotes containing the f string and the string
variable used in the f string should be
different.
If using single quotes for the string variable,
use double quotes for the f module and vice versa.
An answer using the format() command is above, but you may want to look into the Decimal standard library object if you're working with floats that need to represent an exact value. You can set the precision and rounding in its context class, but by default it will retain the number of zeros you place into it:
>>> import decimal
>>> x = decimal.Decimal('2.0000')
>>> x
Decimal('2.0000')
>>> print x
2.0000
>>> print "{0} is a great number.".format(x)
2.0000 is a great number.

Categories