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 youstring
? – 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
2 Answers
Reset to default 4Try 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.