parseFloat() function or by using the
parseFloat() function (removes trailing zero decimals only)
A thing to note is that when a number value is set, it will not contain any trailing decimal zeros. So for example, the number 11454500.0200 will be set as 11454500.02.
However, the only situation you’ll meet this issue is when you have a string that is formatted as a number. There lies the solution above, you only need to convert the string into a number, specifically afloat. And to do that, you simply need to use the
Number class’ static
Number.parseFloat() (or simply shortened to the
So with that in mind, we have:
const strNum = "12345.67000000"; const num = parseFloat(strNum); const newStrNum = num; console.log(newStrNum);
A second method would be to use the
.toFixed() function, though please note that there are multiple issues with this function.
.toFixed() function takes a number and reformats them into a string with a fixed point, i.e., the number will always have exactly
decimals number of decimals. If the
decimals is smaller than the number of decimals in total, it will round the decimal after the
decimals. On the other hand, if
decimals is greater than the number of decimals in total, it will pad out zeros at the end to compensate.
So for example:
const num = 12345.67000000; const fixedNum = num.toFixed(2); console.log(fixedNum);
While this may seem fine on its own, there lies the issue:
- You need to do it check manually what decimal the first trailing zero is, hence automation in this case is extremely cumbersome.
- If the
decimalsis larger than the index of the first trailing zero, it will not remove the zeros and at worse create more
- If the
decimalsis smaller than the index of the first trailing zero, it will round the decimals behind it, changing the value.
With all of that in consideration, it is highly unadvised that you use this method.
.toFixed() function finds more utility in displaying numbers. Such as displaying irrational numbers or formatting dollars. For example:
const num = 1/3; const money = 12.59431; console.log(num.toFixed(3)); console.log("$" + money.toFixed(2));
parseFloat() function or use the
.toFixed() function, though note that the latter method is highly unadvised and has more utility in displaying numbers.
Maybe you are interested: