最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Subtraction in JavaScript only returns two digits of the thousands - Stack Overflow

programmeradmin2浏览0评论

I have two variables holding integer values:

x = 36,000;
y = 18,045.40;

this is how i subtract:

z = parseInt(x) - parseInt(y);

the result is 15.

If i remove the parseInt the result is 'Nan'.

How do I go about subtracting x with y without rounding off or removing thousands?

many thanks.

I have two variables holding integer values:

x = 36,000;
y = 18,045.40;

this is how i subtract:

z = parseInt(x) - parseInt(y);

the result is 15.

If i remove the parseInt the result is 'Nan'.

How do I go about subtracting x with y without rounding off or removing thousands?

many thanks.

Share Improve this question edited Dec 13, 2011 at 17:09 MacMac 35.4k55 gold badges153 silver badges224 bronze badges asked Dec 13, 2011 at 16:50 Saint DeeSaint Dee 1,0156 gold badges22 silver badges43 bronze badges 1
  • Don't gave mas in your value, also see this demo : Fiddle for this in which you have a idea to subtract two floating values even it is a positive or negative value... – lk.annamalai Commented Feb 21, 2013 at 5:07
Add a ment  | 

3 Answers 3

Reset to default 6

Don't put mas in your numbers.

The code you have posted won't even run. I would remend pulling the ,s out of your numbers and using parseFloat instead. This appears to give the result you want. Demo here:

http://jsfiddle/yVWA9/

code:

var x = 36000;
var y = 18045.40;

alert(parseFloat(x) - parseFloat(y));

There is no separator for thousands in Javascript. Your variables are either holding strings and not integer values or you are getting syntax error.

If you have strings and they cannot be changed (like received from service, etc.) then try this:

x = "36,000";
y = "18,045.40";

// remove mas and convert to numbers
function norm(num) { return +num.replace(',', ''); }

console.log(norm(x) - norm(y));
发布评论

评论列表(0)

  1. 暂无评论