BaconJuice
BaconJuice

Reputation: 3769

How to extract a number from a string with decimals using javascript

Hey Folks I'm trying to extract the amount from a variable that looks something like this.

var amountStr  = "iPhone ($45.00)";

I've tried the following code to extract it

var amountNum= amountStr.replace( /^\D+/g, '');

how ever the output is as follows

45.00)

Could someone let me know how I should go about dropping the last ')' in a cleaner way?

Thank you.

Upvotes: 1

Views: 64

Answers (2)

Mustafa sabir
Mustafa sabir

Reputation: 4360

Use substring method and specify the indices of the amount between both the brackets (which can be found out by having the indices of brackets)

var amountStr  = "iPhone ($45.00)";
var n1 = amountStr.indexOf("(");
var n2 = amountStr.indexOf(")");    
var amountNum= amountStr.substring(n1+2, n2)  

Upvotes: 0

Alex
Alex

Reputation: 14618

You have a "beginning of text" marker in your regex. This is why it doesn't match the dot, or the parenthesis.

var amountNum= amountStr.replace( /\D+/g, '');

will replace all non-digits in a string. However you need your dot in place, thus this should be used:

var amountNum= amountStr.replace( /[^\d\.]+/g, '');

Next, to make sure that you actually have a number (not a string), so you can perform correct adding, use this:

var amountNum = parseFloat(amountStr.replace( /[^\d\.]+/g, ''));

But, in case you have strings like "iPhone3 ($45.00)", the result will be 345, instead of 45. You need to find exactly what you need in this string, instead of looking for what you don't need. An example would be this:

var amountNum = parseFloat(amountStr.match( /\d+(\.\d+)?/g)[0]);

This will also not work with "iPhone3", but at least you won't have 345, but just 3.

So just look for the last number, like this:

var amountNum = parseFloat(amountStr.match( /\d+(\.\d+)?/g).pop());

Upvotes: 3

Related Questions