在Javascript中正确格式化两个小数点的钱

时间:2016-02-01 12:39:10

标签: javascript

我试图在我的代码中将钱正确格式化为两个小数点。 当我添加数量10时,我得到的返回值为449.90000000000003。 我想看看449.90。这是我的代码,我似乎无法让它工作。

<html>
<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> 


<script type='text/javascript'>
$(window).load(function(){
$('#quantity').on('keyup',function(){
    var tot = $('#price').val() * this.value;
    parseFloat(Math.round(tot * 100) / 100).toFixed(2);
    $('#total').val(tot);
});

});
</script>  

  </head>
  <body>  
    <table>                        

      <caption>Checkout Time!</caption>                    
      <thead>                        
        <tr>                                                         
          <th>Quantity</th>                                                        
          <th>Total</th>                        
        </tr>                    
      </thead>                                                

      <tbody>                        
        <tr>                                    
            <td><input type="text" id="quantity" value="1"/></td>
            <td><input type="text" id="total" readonly value="44.99"/></td>                        
        </tr>                    
      </tbody>                      

      <tfoot>                        
        <tr>                            
          <td colspan="4" align="right">
          <input type="hidden" id="price" readonly value="44.99" />
            <input type="button" value="Checkout!"/></td>                        
        </tr>                    
      </tfoot>                                    

    </table>  
</body>
</html>

3 个答案:

答案 0 :(得分:1)

您需要

的作业
parseFloat(Math.round(tot * 100) / 100).toFixed(2);

答案 1 :(得分:0)

更改此代码:

$('#quantity').on('keyup',function(){
    var tot = $('#price').val() * this.value;
    var new_tot = parseFloat(Math.round(tot * 100) / 100).toFixed(2);
    $('#total').val(new_tot);
});

答案 2 :(得分:0)

尝试

tot = parseFloat(Math.round(tot * 100) / 100).toFixed(2);
相关问题