Javascript十进制减法

时间:2014-12-17 19:03:03

标签: javascript

我在Firefox控制台上尝试此代码,但我不知道如何得到正确答案(0.11)。我想了解为什么这段代码没有像我预期的那样工作。有人可以帮助我理解。谢谢!

  var a = "12,25";
  var b = "12,14";

  console.log("A: " + a);
  console.log("B: " + b);

  var parsedA = parseFloat(a.replace(',', '.'));
  var parsedB = parseFloat(b.replace(',', '.'));

  console.log('Parsed A: ' + parsedA);
  console.log('Parsed B: ' + parsedB);

  console.log("Dif Parsed Float: " + (parsedA - parsedB));

  var numberA = Number(a.replace(',', '.'));
  var numberB = Number(b.replace(',', '.'));

  console.log('Number A: ' + numberA);
  console.log('Number B: ' + numberB);

  console.log("Dif Number: " + (parsedA - parsedB));

1 个答案:

答案 0 :(得分:0)

只需使用toFixed(2)作为结果

  var a = "12,25";
  var b = "12,14";

  console.log("A: " + a);
  console.log("B: " + b);

  var parsedA = parseFloat(a.replace(',', '.'));
  var parsedB = parseFloat(b.replace(',', '.'));

  console.log('Parsed A: ' + parsedA);
  console.log('Parsed B: ' + parsedB);

  console.log("Dif Parsed Float: " + (parsedA - parsedB));

  var numberA = Number(a.replace(',', '.'));
  var numberB = Number(b.replace(',', '.'));

  console.log('Number A: ' + numberA);
  console.log('Number B: ' + numberB);

  console.log("Dif Number: " + (parsedA - parsedB).toFixed(2)); //<<< here