how to do round half even in javascript unlimited digits after point?

怎甘沉沦 提交于 2019-12-23 21:30:07

问题


I want to have 26.955 rounded to 26.96

I mean if I have numbers 0-4 I want to round them down and if they are 5-9 I want to round them up

I considered parseFloat(number).toFixed(2) however it returns me 26.95, I need 26.96 I used Math.round but this doesn't work either, I saw Math.round10 but it told me this function doesn't exist so I don't know how to solve my problem.

UPDATE: I don't have always 3 digits after point I have more than that I would have 26.956736489

your mentioned duplicate talks about .fixed(2) I am saying it is not working for half even it is not a duplicate


回答1:


Try

Math.round(29.955*100)/100; //29.96

Or cool functional approach

function round(n) {
   n = Math.pow(10,n);
   return function(num) {
       return Math.round(num*n)/n;
   }
}

var round2 = round(2);
var num = 29.9555;
console.log(round2(num));



回答2:


use this:

var num=26.955
Math.round(num* 100) / 100;


来源:https://stackoverflow.com/questions/26806234/how-to-do-round-half-even-in-javascript-unlimited-digits-after-point

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!