Animay
Animay

Reputation: 630

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

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;

Upvotes: 1

Views: 5289

Answers (2)

Aparna
Aparna

Reputation: 622

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

Upvotes: 4

Magus
Magus

Reputation: 15104

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.

Upvotes: 2

Related Questions