Number toFixed(2) in Js if decimal have

generally, to fix the number in javascript we write the toFixed(2) function. I want to make a function for numbers when a number has a decimal like 12.326252 it will show 12.33 and when it has no decimal like 123 it will show 123, not 123.00.
means if decimal when adding auto .toFixed(2) else not.
How I active the goal

I wrote the code but it not working, please help to fix this bug.

number = 20.526
function check(number) {
    if (number == Math.floor(number)) {
        //console.log(number)
        return number;
    } else {
        //console.log(number.toFixed(2))
        return number.toFixed(2);
    }
}
check(number);

Hi @wawane7256, note that toFixed() is a formatting method and returns a string not a number; if this is what you want, you might use a regular expression to remove the .00 suffix:

number.toFixed(2).replace(/\.00$/, '')

If you want an actual number though just convert it using Number() and you won’t get the trailing zero decimals:

Number(number.toFixed(2))

Or another way without intermediary string conversion:

Math.floor(number * 100) / 100
2 Likes

When I write this code below it not working and calculating please help me how do I fix this issue.

function number(number) {
  if (number == Math.floor(number)) {
    return number;
  } else {
    return Number(Number(number).toFixed(2).replace(/\.00$/, ""));
  }
};
console.log(number("10.510" + 10)); OR
console.log(number("10.510") + "10"); OR
console.log(number(10.510) + "10"); 

//expected output: 20.51

None of these are workable. Adding a number to a string results in a concatenated string — it’s called ‘type coercion’.

"10.510" + 10 === "10.51010" 
10 + "10.510" === "1010.510"

You need to convert the strings to numbers first.

Edit:
Looking at @m3g4p0p’s solutions this is the one I like the most.

const formatNumber = (numString) => Math.round(numString * 100) / 100
1 Like