我正在尝试格式化一个字符串以在小数点后显示两个数字。我想在不使用“数学”等内置方法的情况下执行此操作。我有可以做到这一点的东西,但是当数字只是“4.5”时就会出现问题,例如,我需要在上面添加一个 0,但我遇到了麻烦。这是到目前为止我的代码。
function toFixed(num){
let elem = "";
// let x = "";
for (let i = 0; i < num.length; i++) {
if(num[i - 2] === '.'){ // num[i] happens to be the third 8
break;
}
// elem += num[i];
elem += num[i];
elem += "0";
}
return elem
}
console.log(toFixed("7.88888888")) // "7.88"
console.log(toFixed("77645345.987654")) //77645345.88
console.log(toFixed("1")) // "1.00"
console.log(toFixed("4.5")) // "4.50"
现在我在每个数字后面都看到了 0。
最佳答案
没有数学
:
function toFixed(num) {
let [a, b = ""] = num.split(".");
b += "00";
return `${a}.${b.slice(0, 2)}`;
}
console.log(toFixed("7.88888888")) // "7.88"
console.log(toFixed("77645345.987654")) // "77645345.98"
console.log(toFixed("1")) // "1.00"
console.log(toFixed("4.5")) // "4.50"
没有任何内置方法:
function toFixed(num) {
const len = num.length;
let result = "";
for (let i = 0; i < len; i++) {
const c = num[i];
if (c === ".") {
return `${result}.${num[i + 1] || 0}${num[i + 2] || 0}`;
}
result += c;
}
return `${result}.00`;
}
console.log(toFixed("7.88888888")) // "7.88"
console.log(toFixed("77645345.987654")) // "77645345.98"
console.log(toFixed("1")) // "1.00"
console.log(toFixed("4.5")) // "4.50"
关于javascript - 创建一个函数,将字符串格式化为始终在小数点后显示两位有效数字,而不使用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61265014/