Nanfeng

Notes on software development, code, and curious ideas

Remove Decimal Trailing Zeros in TypeScript Without Losing String Precision

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function removeTrailingZeros(numberString: string): string {
const trimmedString = numberString.trim();
const decimalIndex = trimmedString.indexOf('.');

if (decimalIndex !== -1) {
let endIndex = trimmedString.length - 1;

while (trimmedString[endIndex] === '0') {
endIndex--;
}

if (trimmedString[endIndex] === '.') {
endIndex--;
}

return trimmedString.slice(0, endIndex + 1);
}

return trimmedString;
}

console.log(removeTrailingZeros('3.1400')); // "3.14"
console.log(removeTrailingZeros('10.00')); // "10"
console.log(removeTrailingZeros('5.50')); // "5.5"

The function trims surrounding whitespace, removes zeros only from the fractional portion, and also removes the decimal point if no fractional digits remain. Unlike converting through Number, this preserves the input as a string and avoids changing large values through floating-point parsing.

+