Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

😳 保留后2位小数点,并且累加得到总价问题?变成了字符相加? #11

Open
heycqing opened this issue Sep 8, 2018 · 0 comments

Comments

@heycqing
Copy link
Owner

heycqing commented Sep 8, 2018

具体详情如下:

要求:


  • 保留2位小数点,把增加还是减少的数进行最后累加

错误的做法

使用了 toFixed() 函数来保留2位小数;

     // 转换 Number 数据类型,保留2位小数  
        var fix2 =  items[i].price;
        var num_price = new Number(fix2)  ;
        var num_2 = num_price.toFixed(2);

当你使用 toFixed() 的时候,x.toFixed()x 必须是 Number


按道理来说是没问题的,结果是得到了 保留2位小数的数 , 但是当你累加的时候,会出现一个情况就是:

你累加的结果是字符串相加的情况。


原因在于: toFixed() 是返回格式化的字符串


如何解决?

可以使用 Math.round() 函数

  • 具体写法是;
          var num_price = new Number(fix2)  ;
          var num_2 = Math.round(num_price * 100)/100;

这样就可以得到保留2位小数的值,并且是按照数学累加得到总值

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant