南锋

南奔万里空,脱死锋镝余

ts数字字符串去掉后面的0

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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;
}

// 示例用法
const numberString1 = '3.1400';
const result1 = removeTrailingZeros(numberString1);
console.log(result1); // 输出: "3.14"

const numberString2 = '10.00';
const result2 = removeTrailingZeros(numberString2);
console.log(result2); // 输出: "10"

const numberString3 = '5.50';
const result3 = removeTrailingZeros(numberString3);
console.log(result3); // 输出: "5.5"

+