zoukankan      html  css  js  c++  java
  • 转 累加含小数点的数据:parseFloat、toFixed等

    【前端填坑】累加含小数点的数据:parseFloat、toFixed等

    1.  
      <script type="text/javascript">
    2.  
      //要求:累加含有两位小数点的数据
    3.  
      var numbs = ['545.6','172.95','936.93','200','43.2','202.65','8573.9','171.92','72.69',
    4.  
      '280','662.11','12.6'];
    5.  
       
    6.  
      //出错方法:
    7.  
      var amount = 0;
    8.  
      for(var i = 0;i < 12;i++){
    9.  
      amount += parseFloat(numbs[i]);
    10.  
      }
    11.  
      console.log("直接使用parseFloat计算结果:"+amount);//11874.550000000001
    12.  
       
    13.  
      //方案一:通过parseFloat累计,然后再使用toFixed进行四舍五入
    14.  
      var amount1 = 0;
    15.  
      for(var i = 0;i < 12;i++){
    16.  
      amount1 += parseFloat(numbs[i]);
    17.  
      }
    18.  
      console.log("toFixed计算结果:"+amount1.toFixed(2));//11874.55
    19.  
       
    20.  
      //方案二:通过乘以100,再除以100.这样可以将var类型转换成number类型
    21.  
      var amount2 = 0;
    22.  
      for(var i = 0;i < 12;i++){
    23.  
      amount2 += numbs[i] * 100;
    24.  
      }
    25.  
      amount2 = amount2 / 100;
    26.  
      console.log("*100/100计算结果:" + amount2);//11874.55
    27.  
       
    28.  
  • 相关阅读:
    the core or essence of a computer
    HEXADECIMAL NOTATION is Syntactic_sugar.
    Converting from Decimal Notation to Binary Notation for Fractions
    convert from base 10 to base 2
    MYSQL PASSWORD()
    Environment Variables
    Why Stored Procedures?
    delimiter
    page fault rate
    Segmentation
  • 原文地址:https://www.cnblogs.com/ZJ0065/p/10731613.html
Copyright © 2011-2022 走看看