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

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 con

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744836764a4596309.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信