0

I have a String Like This:

"Dark Bronze - add $120.00"

I need to pull the 120 into a float number variable.

How would I do that?

1
  • A string isn't code, would you be able to post the mark-up surrounding that string? Commented Mar 29, 2011 at 21:45

5 Answers 5

5
var str = "Dark Bronze - add $120.00";
var val = str.match(/\$[0-9]*\.[0-9]*/)[0];
var f = Number(val.substring(1));

// (f is a number, do whatever you want with it)
Sign up to request clarification or add additional context in comments.

3 Comments

I agree, using regex instead of substring/slice helps to protect against characters that could come after the the number
+1, but rather than calling toString() on the result, you should just select the first element [0].
@Box9: Thanks for pointing that out (forgot to update that before posting)
1
var input = 'Dark Bronze - add $120.00',
    toParse = input.substring(input.indexOf('$') + 1),
    dollaz = parseFloat(toParse);

alert(dollaz);

Demo →

Comments

1
var str="Dark Bronze - add $120.00", val;
val = parseFloat(str.slice(str.indexOf('$')));
alert('The value is ' + val);

Comments

0
var str = 'Dark Bronze - add $120.00';
var pos = str.indexOf('$');
if (pos < 0) {
    // string doesn't contain the $ symbol
}
else {
    var val = parseFloat(str.substring(pos + 1));
    // do something with val
}

Comments

0
var str = "Dark Bronze - add $120.00";

/*
[\$£¥€] - a character class with all currencies you are looking for
(       - capture
\d+     - at least one digit
\.      - a literal point character
\d{2}   - exactly 2 digits
)       - stop capturing
*/
var rxp = /[\$£¥€](\d+\.\d{2})/;

// the second member of the array returned by `match` contains the first capture
var strVal = str.match( rxp )[1];

var floatVal = parseFloat( strVal );
console.log( floatVal ); //120

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.