skip to Main Content

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:

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?

enter image description here

2

Answers


  1. 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.

    Login or Signup to reply.
  2. 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)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search