3

I am just dipping my toe into the confusing world of javascript, more out of necessity than desire and I have come across a problem of adding two integers.

1,700.00 + 500.00

returns 1,700.00500.00

So after some research I see that 1,700.00 is being treated as a string and that I need to convert it.

The most relevant pages I read to resolve this were this question and this page. However when I use

parseInt(string, radix)

it returns 1. Am I using the wrong function or the an incorrect radix (being honest I can't get my head around how I decide which radix to use).

var a="1,700.00";
var b=500.00;
parseInt(a, 10); 
1
  • parseFloat ? I don't think you can parse numbers 1,700.00, which number do you expect as output? Commented Mar 12, 2014 at 7:47

4 Answers 4

4

Basic Answer

The reason parseInt is not working is because of the comma. You could remove the comma using a regex such as:

var num = '1,700.00';

num = num.replace(/\,/g,'');

This will return a string with a number in it. Now you can parseInt. If you do not choose a radix it will default to 10 which was the correct value to use here.

num = parseInt(num);

Do this for each of your string numbers before adding them and everything should work.

More information

How the replace works:

More information on replace at mdn:

`/` - start  
`\,` - escaped comma  
`/` - end  
`g` - search globally

The global search will look for all matches (it would stop after the first match without this)
'' replace the matched sections with an empty string, essentially deleting them.

Regular Expressions

  • A great tool to test regular expressions: Rubular and more info about them at mdn
  • If you are looking for a good tutorial here is one.

ParseInt and Rounding, parseFloat

parseInt always rounds to the nearest integer. If you need decimal places there are a couple of tricks you can use. Here is my favorite:

2 places: `num = parseInt(num * 100) / 100;`
3 places: `num = parseInt(num * 1000) / 1000;`

For more information on parseInt look at mdn.

parseFloat could also be used if you do not want rounding. I assumed you did as the title was convert to an integer. A good example of this was written by @fr0zenFry below. He pointed out that parseFloat also does not take a radix so it is always in base10. For more info see mdn.

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

2 Comments

That has worked, thankyou. Could you offer a bit of clarity to .replace(/\,/g,''); and why parseInt drops the .00 at the end of the string please?
+1 Thanks for noting my point in your answer. I have updated my answer with alternate solution to yours(for decimal places). Your approach may be better if one wants to make comparison after adding the numbers. I used toFixed() which converts the number back to string.
4

Try using replace() to replace a , with nothing and then parseFloat() to get the number as float. From the variables in OP, it appears that there may be fractional numbers too, so, parseInt() may not work well in such cases(digits after decimal will be stripped off).

Use regex inside replace() to get rid of each appearance of ,.

var a = parseFloat('1,700.00'.replace(/,/g, '')); 
var b = parseFloat('500.00'.replace(/,/g, ''));
var sum = a+b;

This should give you correct result even if your number is fractional like 1,700.55.

If I go by the title of your question, you need an integer. For this you can use parseInt(string, radix). It works without a radix but it is always a good idea to specify this because you never know how browsers may behave(for example, see comment @Royi Namir). This function will round off the string to nearest integer value.

var a = parseInt('1,700.00'.replace(/,/g, ''), 10);   //radix 10 will return base10 value
var b = parseInt('500.00'.replace(/,/g, ''), 10);
var sum = a+b;

Note that a radix is not required in parseFloat(), it will always return a decimal/base10 value. Also, it will it will strip off any extra zeroes at the end after decimal point(ex: 17500.50 becomes 17500.5 and 17500.00 becomes 17500). If you need to get 2 decimal places always, append another function toFixed(decimal places).

var a = parseFloat('1,700.00'.replace(/,/g, '')); 
var b = parseFloat('500.00'.replace(/,/g, ''));   
var sum = (a+b).toFixed(2);    //change argument in toFixed() as you need
// 2200.00

Another alternative to this was given by @EpiphanyMachine which will need you to multiply and then later divide every value by 100. This may become a problem if you want to change decimal places in future, you will have to change multiplication/division factor for every variable. With toFixed(), you just change the argument. But remember that toFixed() changes the number back to string unlike @EpiphanyMachine solution. So you will be your own judge.

6 Comments

do you know where the input comes from ? it might be input from a stupid user input or incorrect flow like function getMeTheNumber(){return 010.toString();}; alert(parseFloat(getMeTheNumber().replace(/,/g, ''))) and your code will fail. why not specify radix ? you should build robust code.
@RoyiNamir: again same answer from me: parseFloat() doesn't take radix. It can work only with base10 (i.e., decimal values). It is applicable only for parseInt(). #ref1, #ref2, #ref3
@RoyiNamir: Here is another nice reference you will love.
This doesn't seem to retain the .oo. How I can retain the numbers after the decimal place?
@tony09uk: updated my answer. Also, note that toFixed() will convert the number into string. So, comparison may not work on the result.
|
3

try this :

parseFloat(a.replace(/,/g, ''));

it will work also on : 1,800,300.33

Example :

parseFloat('1,700,800.010'.replace(/,/g, '')) //1700800.01

6 Comments

No it will not work on 1,800,300.33. With parseInt('1,800,300.33'.replace(/,/g, ''), 10);, it becomes 1800300. See my answer, parseFloat() should be used instead.
I guess, a radix is not required too.
@Fr0zenFyr parseInt('010') in ie8 returns 8. if you see a hole , dont try to block the hole. go around it.
Here we are talking about parseFloat(), does this rule apply here too? You are confusing it with parseInt(), parseFloat() doesn't take second argument, it takes only decimal. Correct me if I'm wrong.
@Fr0zenFyr it will be required if the argument is number parseFloat(010) which is 8 ( ie8 , heck -010 is 8). this is not the OP case since his input is string. but again whats the problem with specifying radix to be sure for all cases ?
|
0

Javascript doesn't understand that comma. Remove it like this:

a.replace(',', '')

Once you've gotten rid of the comma, the string should be parsed with no problem.

2 Comments

this will replace only the first occurrence.
@RoyiNamir: Good point, you're right. TBH I barely use Javascript. Go ahead and write a better answer and I will upvote it.

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.