How to get specific number of digits? Python [duplicate] - python

This question already has answers here:
How to round to 2 decimals with Python? [duplicate]
(21 answers)
Closed 4 years ago.
How would I format my float digits so that there is always 7 digits no matter the direction?
The value could be any of the following but I always want 7 like below
0.0054233
1234567
123.1224
1.992923
The portion I have right now is
return "%.7f" % fd
How can I adjust that to get my desired output? or maybe link me to something similar I could try and read from..>?

Try if this can work for you:
n = 123.456789
decimals = 7 - len(str(int(n)))
print('{:.{prec}f}'.format(n, prec=decimals))
#=> 123.4568
The drawback is that it rounds up.

It depends on the context of the program, in my opinion... If you just want the numbers to the right to be 6 decimals, use:
"{:.6f}".format(whatevervar)
In other contexts maybe convert it to a string and use len() to evaluate the number of digits.
Hope this helps!
EDIT: Seeing your comments, I would recommend using a conditional to define what you are trying to do. When the number has no decimals (check this thread for how to do it: How to check if a float value is a whole number ) leave it as it is, when it has decimals, round it up with the code I posted above.

Related

How to count decimals of an input? [duplicate]

This question already has answers here:
Determine precision and scale of particular number in Python
(11 answers)
Closed 2 years ago.
I want to know how many decimals an input has to then use that information to aproximate the result of an operation to the same number of decimals. For example:
example = float(input('n '))
Imagine the input is 1.99, how do I obtain the number of decimals (2) to then use it?
Here's a simple hack to it.
dec = len(str(example).split('.')[1])

Is there a Math function to strip off decimals from a float (in Python)? [duplicate]

This question already has answers here:
Splitting a number into the integer and decimal parts
(9 answers)
How to get numbers after decimal point?
(37 answers)
Closed 2 years ago.
If I have a float like 32.879, and I want to end up with just 0.879, I can think of a few ways to do it, like:
Convert to string, strip off everything before the ., convert back to float; OR
32.879 - int(32.879)
Both of those feel like hacks. Is there no pure math operation that can do this?
Sort of like using abs() instead of if x < 0: x = x*-1
I'm dealing with Python, but if anyone can tell me the math name for this operation, I can probably google the Python way to do it.

error when trying to separate a integer from a decimal [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 2 years ago.
I'm trying to create a module that will separate the decimal from a number as I need it for a project.
However when I test it the integer comes out fine but the decimal always gets an error:
def seperate(decimal):
integer = int(decimal)
dec = decimal-integer
print(dec, integer)
if I say try to enter 2015.677 it give this: 0.6769999999999072 2015
what is wrong?
Actually what i suggest is that you can try this alternative approach,
And for this to work properly we always need to pass a floating value to it, and it also works for your conditions
def seperate(decimal):
integer = int(decimal)
decimal = str(decimal)
dec = decimal[decimal.index('.')+1:]
return(int(dec), integer)
what's the error you are getting?
I tried your code, and it worked just fine on Python 3.7
decimal = 3.5
integer = int(decimal)
dec = decimal-integer
print(dec, integer)
If you give us the error, perhaps I can help you a little bit more.
Regards!
Edit:
After reading the update on the rounding problem, i used the "round" function and returned the 0.677 part of your decimal just fine.

Use Python 3 str.format to truncate a float to have no more than x number of digits [duplicate]

This question already has answers here:
Formatting floats without trailing zeros
(21 answers)
Closed 4 years ago.
I am looking for an expression that will truncate a float to at most a certain number of digits. I want to preserve a certain number of decimals, without having unnecessary trailing 0s.
So, this almost works as desired:
"{0:3.f"}.format(number)
For input 3.123000001:
"{0:.3f}".format(3.1230000001)
'3.123'
Great. But for input 3:
"{0:.3f}".format(3)
'3.000'
I figured out the answer while I was writing the question. Just add .rstrip('0') to the expression. So:
"{0:3.f}".format(number).rstrip('0')

How to read '$1,234.56' as 1234.56 [duplicate]

This question already has answers here:
How do I convert a currency string to a floating point number in Python?
(10 answers)
Closed 7 years ago.
I've looked through the 'currency' threads, but they're all for going the other way. I'm reading financial data that comes in as $1,234.56 &c, with everything a string. I split the input line, and want to convert the value item to float for add/subtract (I'm mot worried about roundoff error). Naturally, the float() throws an error.
I could write a function to call as 'amount = float(num(value_string)), but woder if there's a "dollar_string_to_float()" function in one of the 32,000 Python modules.
I think this question is slightly different from this question, but I'm not sure.
Anyway, the code from the afformentioned question just need one function change from Decimal to Float and the removal of the Decimal import.
As you requested, the code is in a dollar_string_to_float function:
>>> from re import sub
>>> def dollar_string_to_float(s):
return float(sub(r'[^\d.]', '', money))
>>> money = '$1,234.56'
>>> print dollar_string_to_float(money)
1234.56
Look into the regular expressions module. You can compile a pattern that matches your dollars/cents format and extract the floating-point number from it.

Categories

Resources