Python - Converting String Numbers To Float - python

I want to convert string numbers on a list to float numbers
and i can't do it, so i need some help.
num = '0.00003533'
print('{:f}'.format(float(num)))
formatting it without decimals, only returns a float of 0.000035, i need the entire string in a float.
print('{:8f}'.format(float(num)))
adding the exact decimal works, but the numbers in the list with decimals varies greatly, so i can't manually add it everytime, how could i automatically add the correct decimal number inside the format?
something like '{':exactdecimalf'} exactdecinal being a variable.
i'm using a module that requires float, which is why i can't print it directly from the string format.

Use this
from decimal import Decimal
num = '0.00003533'
print(Decimal(num)) #0.00003533
if you want to print as string
print ('{:f}'.format(Decimal(num)))

Maybe double precision will suit you.
from decimal import Decimal
print ('{:f}'.format(Decimal(num)))

You can split the string and take the length of the last part with
len(num.split(".")[1])
Then use that as the number of decimals.

Related

Convert Scientific Notation to String

When I load xlsx file. I have a number IBAN with scientific notation.
For example:
7.810500161524e+25
This number should be:
78105001615240000000000000
I want to convert this number to string, but I get result:
'7.810500161524e+25'
I thought if I converted to int and then to string it would be the correct result, but again I get wrong result:
'78105001615239996483043328'
Anyone have any idea?
You can convert your string '7.810500161524e+25' to a decimal.Decimal number without altering its precision at all the way you will if you convert it to a floating point value. Then (if necessary) you can convert the decimal value to an integer or a string.
import decimal
scientific_notation = '7.810500161524e+25'
decimal_number = decimal.Decimal(scientific_notation) # Decimal('7.810500161524E+25')
int_number = int(decimal_number) # 78105001615240000000000000
fixed_point_string = format(decimal_number, 'f') # '78105001615240000000000000'

In Python, how can I get a whole number without decimals from math.sqrt?

import math
a = math.sqrt(25)
print(a)
My output is 5.0, how can I get a 5 (whole number) instead?
You have to check and explicitly convert to integer:
if x == (y := int(x)):
x = y
Or, without the assignment operator:
if x == int(x):
x = int(x)
As of python 3.8, you can use math.isqrt:
math.isqrt(25)
Keep in mind that this will always return an integer, even if the input is not a perfect square.
In a reduced manner, you can use a 1 line if operator to assign an integer value to the result of sqrt if both integer and decimal values are the same:
import math
a = math.sqrt(25)
a = int(a) if int(a)==a else a
print(a)
It depends a little on what exact behavior you want: do you want to just print the number without the decimal, or do you want to round a number to an integer?
For the print statement, Python tries to convert whatever is passed to it to a String in order to print it, and by default it gives floating point numbers decimal places. To stop that, we can use string formatting:
print("{:.0f}".format(a))
What this is doing is making a string (the double quotes "") that contains a special format marker (the curly braces {}). Inside the format marker is the code for the desired behavior (0 decimal places on a floating point number). Then we call the .format method of the string and pass the value (a) we want to be used inside the special format marker.
This looks somewhat arcane and ugly, but is the safest method to print what you want because it does not change 'a' and is easily customizable to other printing behaviors.
For rounding a number and converting it to an int, you can either use int() or round(): both will take in a float and output an integer that will print cleanly (and be an integer for future computation). There is no requirement for the thing being converted to actually be an integer but there is different behavior for the two functions: int returns the value of the first digit of a number, while round returns the rounded value (IE round(1.9) -> 2, int(1.9) -> 1, etc).

Format str to float and increase from 1 decimal to 2 decimal in python

I have a list of prices in 1 decimal place and in string format.
I would like to convert each item into a float, change them to two decimal places and append them to a new list.
price = ["9.8", "8.8" ,"10.9", "11.8", "13.9", "18.9"]
newprice = []
I tried this code but it does not work
for i in range(len(price)):
price2= float(price[i])
price= '{0:.3g}'.format(price2)
newprice.append(price)
Most instructions online teach me how to reduce to 2 decimal places, not increase to two decimal places.
You have a few problems here:
you're replacing price (the list) with price (a string) so your loop fails after one iteration
you want the f format specifier to add trailing zeros
You could also make a few improvements, including not using list indexes, using more modern and Pythonic f-strings, and skipping the interim variable price2:
for i in range(len(price)):
newprice.append(f"{float(price[i]):.2f}")
Or you could use a simple list expression:
newprice = [f"{float(n):.2f}" for n in price]
First of all you need to convert the strings to float you can do that with the method float()
Then you add the format to the number with the method format()
You can try the following code:
price = ["9.8", "8.8" ,"10.9", "11.8", "13.9", "18.9"]
price_f = []
for i in price:
new_price_float=format(float(i),'.2f')
price_f.append(new_price_float)
print(price_f)
[float(i) for i in string_prices] is a simple list comprehension that converts your strings to floats
The decimal places of a float is purely for displaying a value so converting from 1 to 2 decimals is not a thing in the language as adding trailing zeros isn't a different value.
string_prices = ["9.8", "8.8" ,"10.9", "11.8", "13.9", "18.9"]
prices = [float(i) for i in string_prices]
for price in prices:
print(f"{price:.2f}")
Since your numbers are already strings, there's no need to convert them to float. Just split at the decimal point, format the right-most piece, and join back together.
price_parts = price[i].split('.')
price_parts[-1] = price_parts[-1][:2].ljust(2, '0')
newprice.append('.'.join(price_parts))
You may want to add some checking to make sure you don't mangle a number that doesn't have a decimal point.

How to convert exponential value to string format in python?

I'm doing some calculations which give very small decimal numbers for example, 0.0000082
When I'm saving it in a variable, it changes into exponent form. I need the result as a string in the end. So, converting the result using str() is not possible because it keeps the e in the string.
I need the string to have exactly 8 decimal places. Is there any way to do this while keeping the 8 digit precision intact?
Another example: 5.8e-06 should be converted to '0.00000580' The trailing zero in the final string is not important.
I need the string to be used elsewhere. So, this shouldn't be done in the print() function.
The exponential notation is not an inherent property of the number (which is stored as a binary floating point value). It's just the default representation when converting the number to a string with str. You can specify your own formatting options if you convert the number to a string using the format function. Try something like this:
format(5.8e-06, '.8f')
The 8 in the format specifier tells it to use eight digits of precision, while the f requests it to be written as a plain decimal without exponential notation. You can read more about the format notations in the documentation.
Just another idea:
'{0:.7f}'.format(0.0000082)
you can try with :
import decimal
print(str(decimal.Decimal(5.8e-06))[:10])
>>> 0.00000580
print ("{:.6f}".format(1e-4))
will print out
0.000100
You could use print:
>>> number = 1e-08
>>> number
1e-08
>>>print("{:.12f}".format(float(number)))
0.000000010000
or You could convert number and store it in string:
>>> str1 = "{:.12f}".format(float(number))
>>> str1
'0.000000010000'

How to return a decimal after using int() function on a string?

Very basic question. If I set products as 3 and parcels as 2, I get 1. How do I have the last line print 1.5, a decimal, instead of simply 1?
products = raw_input('products shipped? ')
parcels = raw_input('parcels shipped? ')
print "Average Number of products per parcel"
print int(products) / int(parcels)
print float(products) / float(parcels)
If you want real numbers, use float, which represents real numbers. Don't use integers.
In Python 3 you'll get this automatically.
In Python 2 you can do from __future__ import division, then dividing two integers will result in a floating point number.
In either case you can use // instead of / if you decide you really needed an integer result instead. That works in Python 2 even if you don't do the import.
You can also convert either or both of the numbers to float to force a floating point result.
If you want the full decimal value use the below,
from decimal import Decimal
print Decimal(products) / Decimal(parcels)

Categories

Resources