I have a problem on the printing format of console.log(). I want to print floating point on console using JavaScript, such as 8.0. For example:
8.0
var i1 = 4.0; var i2 = 8.0; console.log(i1 + i2);
I want 12.0, but 12 is printed. I can fix this problem?
12.0
12
2
You are looking for
console.log((i1 + i2).toFixed(1));
See https://www.tutorialspoint.com/How-to-format-a-number-with-two-decimals-in-JavaScript
The toFixed() method formats a number with a specific number of digits to the right of the decimal. it returns a string representation of the number that does not use exponential notation and has the exact number of digits after the decimal place.
var sum = i1 + i2; console.log(sum.toFixed(1));
or you can print directly
console.log((i1+i2).toFixed(1))
you can also use toPrecision function. But then you have to send the number of digits you want to print. Like for printing 4.0. if the i1 + i2 = 4
(a+b).toPrecision(2)
Click here to cancel reply.
2
Answers
You are looking for
console.log((i1 + i2).toFixed(1));
See https://www.tutorialspoint.com/How-to-format-a-number-with-two-decimals-in-JavaScript
or you can print directly
you can also use toPrecision function. But then you have to send the number of digits you want to print.
Like for printing 4.0. if the i1 + i2 = 4