gpt4 book ai didi

javascript - 如何在 JavaScript 中四舍五入数百万?

转载 作者:行者123 更新时间:2023-11-30 23:47:06 25 4
gpt4 key购买 nike

我正在尝试对大数字进行四舍五入。例如,如果我有这个号码:

12,645,982

我想四舍五入这个数字并将其显示为:

1300万

或者,如果我有这个号码:

1,345

我想将其四舍五入并显示为:

1000

如何在 JavaScript 或 jQuery 中执行此操作?

最佳答案

这是一个用于格式化千、百万和十亿的实用函数:

function MoneyFormat(labelValue) 
{
// Nine Zeroes for Billions
return Math.abs(Number(labelValue)) >= 1.0e+9

? Math.abs(Number(labelValue)) / 1.0e+9 + "B"
// Six Zeroes for Millions
: Math.abs(Number(labelValue)) >= 1.0e+6

? Math.abs(Number(labelValue)) / 1.0e+6 + "M"
// Three Zeroes for Thousands
: Math.abs(Number(labelValue)) >= 1.0e+3

? Math.abs(Number(labelValue)) / 1.0e+3 + "K"

: Math.abs(Number(labelValue));

}

用法:

   var foo = MoneyFormat(1355);
//Reformat result to one decimal place
console.log(parseFloat(foo).toPrecision(2) + foo.replace(/[^B|M|K]/g,""))

引用文献

关于javascript - 如何在 JavaScript 中四舍五入数百万?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12900332/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com