使用函数将每个数字(也是十进制)转换为字符串,而不会丢失点后的数字

问题描述 投票:0回答:1

我已经尝试了几个小时,希望有一个函数可以将任何数字(包括小数)转换为字符串,而不会丢失零后的数字。

看看结果。如果你通过了 4.0,我会失去点“.0”后面的零。

function convert_number_to_string(n) {
    var n_stringed = n.toString();
    return n_stringed;
}
console.log(convert_number_to_string(4.0))

如何做?

javascript string math
1个回答
0
投票

您可以执行以下操作:

function convert_number_to_string(n) {
    // Check if the number is an integer, if not use toFixed to preserve the decimals
    if (Number.isInteger(n)) {
        return n.toFixed(1); // This ensures at least one decimal place
    }
    return n.toString(); // If it's not an integer, return it as is
}
console.log(convert_number_to_string(4.0))
console.log(convert_number_to_string(4))
console.log(convert_number_to_string(4.0123))

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.