将数字四舍五入到小数点后两位

时间:2020-07-27 10:07:00

标签: javascript

如何在下面的方法中将数字四舍五入到小数点后两位?

<TargetFrameworkVersion>v4.7.1</TargetFrameworkVersion>

我尝试做$('.total').each(function() { var amt = Number($(this).find(".amount").val().replace(/,/g, '')); subtotal += amt; }); ,但没有用,

真的很感谢您的帮助。

3 个答案:

答案 0 :(得分:2)

尝试以下

add_action( 'woocommerce_after_shop_loop_item', 'new_add_to_cart_button' );
function new_add_to_cart_button() {
    // Your button code.
}

答案 1 :(得分:2)

toFixed函数的主要问题是它返回的是字符串而不是数字。

有几种可能的解决方案:

  1. 改进的解决方案

    Number(val.toFixed(2))
    

    OR

    parseFloat(val.toFixed(2))
    
  2. 更多数学方法的解决方案。

    Math.round(val*100)/100
    

答案 2 :(得分:0)

如果value是一个字符串:

parseFloat(amt).toFixed(2);

如果值是数字:

amt.toFixed(2);

或者您可以使用[MDN]中的解决方案[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round]:

function roundToTwo(num) {    
    return +(Math.round(num + "e+2")  + "e-2");
}


  [1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round