【问题标题】:How to round up currency with Jquery [duplicate]如何用Jquery四舍五入货币[重复]
【发布时间】:2020-04-08 04:56:06
【问题描述】:

如何使用 jquery 对不同类型的货币进行四舍五入?我想做的是;

10.30 → 10 //Below .5 will round down
10.60 → 11 //After .5 will round up
849.95 → 850
1,022.20 → 1022

【问题讨论】:

  • 请在提出新问题前进行搜索。舍入是一个简单的概念,已经有许多非常相似的问题。

标签: javascript jquery math currency


【解决方案1】:

您可以使用Math.round()

Math.round() 函数返回四舍五入到最接近整数的数值。

请注意:带逗号的数字是字符串,必须去掉逗号。然后你可以用Number()把它转回数字,最后实现Math.round()

console.log(Math.round(10.30));// → 10 //Below .5 will round down
console.log(Math.round(10.60))// → 11 //After .5 will round up
console.log(Math.round(849.95));// → 850
console.log(Math.round(Number('1,022.20'.replace(/,/g, ''))));// → 1022

【讨论】:

  • 又是我,尝试了您的版本来修复它,但如果货币来自欧洲,我遇到了问题。例如 22,34 欧元。但它与其余部分完美配合。 jsfiddle.net/ug2veqbh
【解决方案2】:

或者您可以使用 jquery 插件:https://github.com/autoNumeric/autoNumeric 那么就这么简单:

new AutoNumeric('.myInput', { 
  roundingMethod: AutoNumeric.options.roundingMethod.halfUpSymmetric 
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-10
    • 1970-01-01
    • 2010-11-13
    • 1970-01-01
    • 1970-01-01
    • 2018-02-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多