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.
Related
This question already has answers here:
Convert decimal mark when reading numbers as input
(8 answers)
Closed 10 months ago.
I take the current exchange rate from the bank's website as a string and I want to convert this string into a number for further calculations and I want to do it as beautifully as possible.
How to convert the string 77,4651 $ to 77.4651 in float format without using func 'replace'?
Use float regular expression to make sure, that you get the float number
txt = "77.4651 $"
x = float(re.search("[-+]?[0-9]*(?:\.?[0-9]*)[1]", txt).string)
or less safe split by spaces
float("77.4651 $".split("\s+")[0])
Regex would be useful here to account for varying formats:
import re
float('.'.join(re.findall('[0-9]+', "77,4651 $")))
This question already has answers here:
Evaluating a mathematical expression in a string
(14 answers)
Closed 1 year ago.
I am trying to take a piece of user input: 5+5 or 5*5 but my code receives it as a string. I want to convert it to an expression from which an answer can be deduced. However, I am not sure how to do this.
For that there's a standard function called as eval.
Examples:
>>> eval("5*5")
25
>>> eval("5+5")
10
>>> eval("2+3*4-4")
10
It will take a string and then calculate the output as per the BODMAS Rule.
Simply use "eval", but unsafe.
This question already has answers here:
How to match a whole word with a regular expression?
(4 answers)
Closed 2 years ago.
I want to find just numbers in textfile so I made this code
r"[+-]? *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?"
but I also get and numbers from string with characters (e.g. my txt file include string a278, and it also find number 278, so I want to not find that kind of numbers)
I want to find just "clear numbers", not a numbers from string which include char.
You can consider look at wordboundaries.
https://www.regular-expressions.info/wordboundaries.html
You could solve such a problem with list comprehension, even without regex, as a simpler solution.
Would have been beneficial if you'd gave us an idea of the type of data you're dealing with i/e of your input data.
Either way considering what you've stated, you want only numbers to be detected without string numbers.
case = "test123,#213 12" output = [int(i) for i in case .split() if i.isdigit()]
output Out[29]: [12]
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.
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.