3

I have a string value that will look like this:

"ZAR 200.15"

Using regex, how can I extract the float value to do calculations with?

For some context, I'm using javascript to access an HTML element's value like this:

var amountDueString = document.getElementById("amountDue").innerHTML;

Then I need to use regex to only get the float value.

var amountDue = amountDueString.match(---some regex---);

I want to extract the float value in order to compare it with user input.

1
  • 3
    Match /\b\d+(?:\.\d+)?/ Commented Jun 28, 2016 at 10:45

5 Answers 5

3

Use regular expression to get number string and then use parseFloat to convert it to floating number

for (var x in arr = ["ZAR 200.15", "20.0", "21", "22.2", "22.20"]) {
  // decimal part only
  console.log(parseFloat(arr[x].match(/(\d+)(\.\d+)?/g)))
}

Sign up to request clarification or add additional context in comments.

Comments

3

Working example.

I think the better way is the one commented by @anubhava :

/\b\d+(?:.\d+)?/

\b : assert position at a word boundary (^\w|\w$|\W\w|\w\W).

\d+ : match a digit [0-9], Quantifier + Between one and unlimited times, as many times as possible, giving back as needed [greedy].

Quantifier ? Between zero and one time, as many times as possible, giving back as needed [greedy].

\. matches the character . literally

Hope this helps.

console.log( "ZAR 200.15".match(/\b\d+(?:.\d+)?/) );

Comments

1

Try this:

(\d)+\.(\d+)

tested on notepad++

1 Comment

Thanks. Using this regex along with parseFloat(), I got the desired result.
1

You can match number with decimals only or numbers with integer and decimal parts:

for (var x in arr = ["ZAR 200.15", "300.0", "1.02", "29.001", "10"]) {
  // decimal part only
  console.log(x, arr[x].match(/(\d+)(\.\d+)?/g))
    // integer + decimal part
  console.log(x, arr[x].match(/(\d+\.\d+)/g))
}

Comments

1

Use the regex to find the floating number and then replace all the other word chars.

var str = "\"ZAR 200.15\"";
var patt = /[^(\d+)\.(\d+)]/g;
var string = str.replace(patt,"");
window.alert(string);

checkout here: here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.