Js sum function() not working properly

I created a function where if the number is the string, float, init, number, or anything the final output will come as valid when we will do any calculation on that.

let num1 = 1.2;
let num2 = 1;
let num3 = "1.2";
let num4 = "1";

I also trying to do if the output has any decimals it will convert to number fixed(2) other will no decimal will show.

My function is correct I thing but when I run the below example it returns the wrong output, please help how to fix it.

function toIntWithFixed(num) {
  if (typeof num === "string") {
    num = Number(num);
  }

  if (num % 1 !== 0) {
    // Convert the decimal value to fixed(2)
    num = Math.round(num * 100) / 100;
  } else {
    // No decimal value, so just return the number
    num = Math.floor(num);
  }

  return num;
}

let num1 = toIntWithFixed(1.114); // 1.11
let num2 = toIntWithFixed(1); // 1
let num3 = toIntWithFixed("0"); // 0
let num4 = toIntWithFixed("0"); // 0

console.log(num1 + num2 + num3 + num4); // expected output 2.114

//but it returning `2.1100000000000003`

that’s a floating point error. You’d have to toIntWithFixed the sum.

As your toIntWithFixed should only return integers I would prefer to do a parseInt() of the returned value

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.