How to extract a floating number from a string
If your float is always expressed in decimal notation something like
>>> import re
>>> re.findall("\d+\.\d+", "Current Level: 13.4db.")
['13.4']
may suffice.
A more robust version would be:
>>> re.findall(r"[-+]?(?:\d*\.\d+|\d+)", "Current Level: -13.2db or 14.2 or 3")
['-13.2', '14.2', '3']
If you want to validate user input, you could alternatively also check for a float by stepping to it directly:
user_input = "Current Level: 1e100 db"
for token in user_input.split():
try:
# if this succeeds, you have your (first) float
print float(token), "is a float"
except ValueError:
print token, "is something else"
# => Would print ...
#
# Current is something else
# Level: is something else
# 1e+100 is a float
# db is something else
How can I extract a floating point number from a string efficiently?
Use this:
float number = Float.parseFloat(s.replaceAll("[^\\d.]", ""));
System.out.println(number);
Or, what's already mentioned in the comments:
Get the substring which only contains the number. Then you can parse it to your data type.
String s = "0.0234000ETH";
String part1 = s.substring(0,8);
float value = Float.parseFloat(part1);
System.out.println(value);
Extracting floating number from string
You can add .
in your Regex:
var t = '1,234.04 km';
var a = t.replace(/[^0-9.]/g, '') // 1234.04
parseFloat(a) // 1234.04
Python: Extract multiple float numbers from string
You could also use regex to do this
import re
s = "38.00,SALE ,15.20"
p = re.compile(r'\d+\.\d+') # Compile a pattern to capture float values
floats = [float(i) for i in p.findall(s)] # Convert strings to float
print floats
Output:
[38.0, 15.2]
how to extract floating numbers from strings in javascript
You can use the regex /[+-]?\d+(\.\d+)?/g
in conjunction with String.match()
to parse the numbers and Array.map()
to turn them into floats:
var regex = /[+-]?\d+(\.\d+)?/g;
var str = '<tag value="20.434" value1="-12.334" />';
var floats = str.match(regex).map(function(v) { return parseFloat(v); });
console.log(floats);
var str2 = '20.434 -12.334';
var floats2 = str2.match(regex).map(function(v) { return parseFloat(v); });
console.log(floats2);
var strWithInt = "200px";
var ints = strWithInt.match(regex).map(function(v) { return parseFloat(v); });
console.log(ints);
See demo code here.
How to extract a floating number from a string but excluding other number in the same string
For this specific example you can use a named capturing group and try something like this:
(?<float>\d+\.\d+)
Here is a quick demo: https://dotnetfiddle.net/Dm78d7
Related Topics
Total Memory Used by Python Process
What Is the Easiest Way to Detect Key Presses in Python 3 on a Linux MAChine
Linux/Python: Encoding a Unicode String for Print
Bash: Variable in Single Quote
How to Deal with Linux/Python Dependencies
Importerror: No Module Named Pytesseract
Ioerror: Can't Read Data (Can't Open Directory) - Missing Gzip Compression Filter
Modulenotfounderror: No Module Named 'Pydip', Although It's Installed
Pandas Column of Lists, Create a Row For Each List Element
Check If a String Contains a Number
How to "Watch" a File for Modification/Change
Getting Another Program's Output as Input on the Fly
How to Find the Target File's Full(Absolute Path) of the Symbolic Link or Soft Link in Python