I need my function to properly format a number or string into a decimal number with X amount of digits after the decimal point. The issue I'm facing is that when I pass 3.0004
to my function, it returns 3
. After reviewing the documentation, I realized that when parseFloat
encounters a .
, it only considers values before that and ignores any invalid characters and those that come after.
Although I understand this behavior, I still want my function to return
3.00
. Is there a way to achieve this? I aim for my function to consistently output a number with specified decimal digits. I chose to useparseFloat
because I require it to return either a number or null.
Below is the code snippet showing my implementation:
const toDecimal = (number: number | string, digits: number = 2): number | null => {
switch (typeof number) {
case 'number':
return parseFloat(number.toFixed(digits));
case 'string':
const parsedDecimal = parseFloat(number);
return isNaN(parsedDecimal)
? null
: parseFloat(parsedDecimal.toFixed(digits));
default:
return null;
}
}
toDecimal(3.0004) // will return 3