0

I am trying to create a script that adds two strings that are pulled from a database. The script pulls the data correctly, but the strings contain a pound sign (£) - so consequently the numbers won't add together as they're effectively text strings.

var subtotal = "£25";
var shipping = "£5";

var total = subtotal + shipping;

How can I strip the pound signs from the code so that the numbers will add up?

Gary
  • 101
  • 1
  • 10
  • 1
    so [replace it](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace) and convert it to a number – epascarello Oct 10 '19 at 17:09
  • 1
    Possible duplicate of [How to remove text from a string?](https://stackoverflow.com/questions/10398931/how-to-remove-text-from-a-string) – Heretic Monkey Oct 10 '19 at 17:33

3 Answers3

0

a simple approach may be

var total = parseFloat(subtotal.replace(/[^.0-9]g/,'')) + parseInt(shipping..replace(/[^.0-9]g/,''));

var subtotal = "£19.99";
var shipping = "£3.95";
var total = parseFloat(subtotal.replace(/[^.0-9]/g,'')) + parseFloat(shipping.replace(/[^.0-9]/g,''));

console.log(total);
console.log(total.toFixed(2)); // to round to 2 decimal places
Dhananjai Pai
  • 5,914
  • 1
  • 10
  • 25
  • 1
    Please search for duplicates before answering questions. – Heretic Monkey Oct 10 '19 at 17:35
  • Thanks. I've given this a go, and it works, except it doesn't add up the numbers after the decimal places: ```` var subTotal = '£19.99'; var Shipping = '£3.95'; var total = parseInt(subTotal.replace('£','')) + parseInt(Shipping.replace('£','')); document.getElementById("demo").innerHTML = "The total of your order is: " + total; ```` – Gary Oct 10 '19 at 17:45
  • just use parseFloat instead – Dhananjai Pai Oct 10 '19 at 17:47
0

You could remove all characters except digits and dots from the string using the string replace method with a regular expression, then call parseFloat on the result to cast it to a number.

const toNumber = n => parseFloat(n.replace(/[^.0-9]/g, ''));
var subtotal = "£25";
var shipping = "£5";

var total = toNumber(subtotal) + toNumber(shipping);

console.log(total);
giuseppedeponte
  • 2,366
  • 1
  • 9
  • 19
0

Thanks to everyone for their help. I've achieved this now as below:

const toNumber = n => parseFloat(n.replace(/[^.0-9]/g, ''));
var subtotal = "£25.53";
var shipping = "£5.30";

var total = toNumber(subtotal) + toNumber(shipping);

document.getElementById("demo").innerHTML =
"The total of your order is: " + total.toFixed(2);

Returns the correct total of 30.83!

Gary
  • 101
  • 1
  • 10