代码语言:javascript复制
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"