如何显示存储在变量中的数字,四舍五入并带有逗号?
How can I display a number stored in a variable rounded and with commas?
我在 Javascript 中的代码涉及操纵多个变量并在屏幕上的计数器中显示其中的一些变量。由于我使用的数学方法,我最终会得到诸如 1842.47167 之类的数字……或类似的数字。我想将数字显示为 1,843(四舍五入并添加了 "thousands" 逗号)。有没有人有简单易行的方法?请参阅下面我尝试过的代码。
console.log(coins) //Output: 1842.4716796875
commaCoins = coins;
commaCoins = Math.round(coins);
commaCoins = coins.toLocaleString();
console.log(commaCoins) //Output: "1,842.472"
//Desired result: 1,843
有人有更好的方法吗?
您需要使用字符串来实现。
类似于:
const coins = 1842.4716796875;
const roundedCoins = Math.round(coins);
const dotFormat = roundedCoins / 1000
const commaFormat = dotFormat.toString().replace('.', ',');
console.log(commaFormat) // Output: 1,842
你显然可以在更少的步骤中做到这一点,如果你需要四舍五入到上层单位,请使用 Math.ceil()。
我在 Javascript 中的代码涉及操纵多个变量并在屏幕上的计数器中显示其中的一些变量。由于我使用的数学方法,我最终会得到诸如 1842.47167 之类的数字……或类似的数字。我想将数字显示为 1,843(四舍五入并添加了 "thousands" 逗号)。有没有人有简单易行的方法?请参阅下面我尝试过的代码。
console.log(coins) //Output: 1842.4716796875
commaCoins = coins;
commaCoins = Math.round(coins);
commaCoins = coins.toLocaleString();
console.log(commaCoins) //Output: "1,842.472"
//Desired result: 1,843
有人有更好的方法吗?
您需要使用字符串来实现。
类似于:
const coins = 1842.4716796875;
const roundedCoins = Math.round(coins);
const dotFormat = roundedCoins / 1000
const commaFormat = dotFormat.toString().replace('.', ',');
console.log(commaFormat) // Output: 1,842
你显然可以在更少的步骤中做到这一点,如果你需要四舍五入到上层单位,请使用 Math.ceil()。