Incorrect calculation result in Javascript

时间:2018-02-03 10:12:46

标签: javascript

My Javascript formula is

total = parseFloat(unit * rate) + 
        parseFloat(rateamount) + 
        parseFloat(((unit * rate) + 
        (rateamount)) * (tax/100));

values are:

unit = 5, rate = 10, rateamount = 10, tax = 10.

The answer it is giving me is 561, which is wrong.

Any help is welcome.

1 个答案:

答案 0 :(得分:1)

Your problem is that you are concatenating strings with this part:

parseFloat(((unit * rate) + (rateamount))

You forgot to parse rateamount which is a string of '10'.

So this Code:

var unit = '5',
  rate = '10',
  rateamount = '10',
  tax = '10';

var total = parseFloat(unit * rate) + parseFloat(rateamount) + parseFloat(((unit * rate) + (rateamount)) * (tax / 100));
console.log(total);

should be like that:

var unit = '5',
  rate = '10',
  rateamount = '10',
  tax = '10'

var total = parseFloat(unit * rate) + parseFloat(rateamount) + parseFloat(((unit * rate) + parseFloat(rateamount)) * (tax / 100));
console.log(total);

Though i wouldn't use parseFloat like that, i would just do it once before any calculations, in order to stay away from bugs like this one.

var unit = '5',
  rate = '10',
  rateamount = '10',
  tax = '10';

var parsedUnit = parseFloat(unit),
  parseRate = parseFloat(rate),
  parsedRateamount = parseFloat(rateamount),
  parsedTax = parseFloat(tax);

var total = parsedUnit * parseRate + parsedRateamount + ((parsedUnit * parseRate) + (parsedRateamount)) * (parsedTax / 100);
console.log(total);