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

javascript - how do i sum of two floats and get a float value in decimal places? - Stack Overflow

programmeradmin1浏览0评论

when i add two numbers in javascript.e.g.,

var a = 4.0;
var b = 4.0;
var c = a+b;

When i print sum in console it gives 8, but i want 8.0, so i did this,

console.log(c.toFixed(1));

and when i checked

console.log(typeof c);

it gives output as string. The problem is that i want output as number and with a decimal place. Even the parseFloat() function did not help.

Overall what i want:

//input
a=4.0;
b=4.0;

//output
a+b = 8.0;

when i add two numbers in javascript.e.g.,

var a = 4.0;
var b = 4.0;
var c = a+b;

When i print sum in console it gives 8, but i want 8.0, so i did this,

console.log(c.toFixed(1));

and when i checked

console.log(typeof c);

it gives output as string. The problem is that i want output as number and with a decimal place. Even the parseFloat() function did not help.

Overall what i want:

//input
a=4.0;
b=4.0;

//output
a+b = 8.0;
Share Improve this question asked Sep 4, 2017 at 11:41 AnimayAnimay 6301 gold badge7 silver badges18 bronze badges 9
  • 8 8.0 is 8 as a number ... if you want 8.0 you can only have 8.0 as a string - javascript doesn't "know" you want 1 decimal ... what if you wanted 8.00, would it have to store that differently to 8.0? – Jaromanda X Commented Sep 4, 2017 at 11:43
  • A number has as many decimal places as you want - it only matters when you turn it into a string. – Evan Knowles Commented Sep 4, 2017 at 11:43
  • typeof(c) gives you string? – James Thorpe Commented Sep 4, 2017 at 11:44
  • console.log(8 === 8.0) – baao Commented Sep 4, 2017 at 11:44
  • where do you want a number with places? – Nina Scholz Commented Sep 4, 2017 at 11:44
 |  Show 4 more ments

2 Answers 2

Reset to default 4

Try parseFloat() with toFixed()

var a = 4.0;
var b = 4.0;
var c = a+b;
console.log(parseFloat(c).toFixed(1)); -- 8.0
console.log(typeof c); -- number

toFixed retuns a string. And it have to returns a string because this is only way you have to output something like 8.0.

If you try console.log(8.0), you'll get 8. This is how the console output works and you can't really go against it.

发布评论

评论列表(0)

  1. 暂无评论