1

Background: I would like to add and subtract numbers. I'm using HTML data-attributes. parseInt() and Number() aren't working as I thought they would be.

   <div class="originalNumber" data-original-number="1,000,000">1,000,000</div>

   <div class="bucket1" data-bucket="100,000">100,000</div>
   <div class="bucket2" data-bucket="200,000">200,000</div>
   <div class="bucket3" data-bucket="300,000">300,000</div>

I get the original number:

   var getOriginal=$(".originalNumber").data("original-number");

console.log = 1,000,000

Now I would like to add and subtract from it. For example click bucket1 and 1,000,000 becomes 900,000 (1,000,000-100,000)

The problem is that I cannot turn the string into a number. I've tried using parseInt() and Number() to no avail.

   var getOriginal=parseInt(getOriginal);
   console.log(getOriginal);

returns 1

    var getOriginal=Number(getOriginal);
    console.log(getOriginal);

returns NaN

What am I missing here?

3 Answers 3

2

Try using a regex:

 var getOriginalNumeric = parseInt(getOriginal.replace(/[^\d\.]/gi, ''));

This will strip out anything but digits and decimals.

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

Comments

1

You'll need to remove all the commas from the string containing the number before using parseInt().

This question has some information on the best ways to do that.

Comments

1

The problem is that a comma is interpreted as the decimal sign, this is standard for most countries, but the US (for example) uses periods as the decimal separator.

You'd need to replace the comma's:

getOriginal = parseInt(getOriginal.replace(/,/g, ""), 10);

Here's a live example: http://codepen.io/TheDutchCoder/pen/WbbzJL

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.