javascript 四舍五入; js 四舍五入

 

方法 Math.round

round() 方法可把一个数字舍入为最接近的整数。

对于 0.5,该方法将进行上舍入。

例如,3.5 将舍入为 4,而 -3.5 将舍入为 -3。

Math.round(748.58)   结果:749

Math.round(748.5867*100) 结果:74859

Math.round(748.5867*100)/100  结果:748.59  保留两位

Math.round(748.5867*1000)/1000  结果:748.587  保留三位

通用js方法:

function format45(val,v2) {
    if (isNaN(val) || val == undefined || val == null) { return null; }
    return Math.round(val * v2) / v2;
}

format45(748.586767,10000)  结果:748.5868

相关文档:http://www.w3school.com.cn/jsref/jsref_round.asp

 若用vue开发,建议放到公共方法类,固定函数名称和精确度,方便统一维护

let util = {

};
util.formatZeroDecimalPlaces = function (val) {
  if (val == undefined || val == null || typeof (val) !== 'number') { return null; }
  let v2 = 1;
  return Math.round(val * v2) / v2;
};
util.formatThreeDecimalPlaces = function (val) {
  if (val == undefined || val == null || typeof (val) !== 'number') { return null; }
  let v2 = 1000;
  return Math.round(val * v2) / v2;
};
export default util;
 
四舍五入也可以通过 toFixed(2) ,但注意它的返回值是string类型,计算的时候需要转换数据类型。
详情见:https://www.cnblogs.com/hao-1234-1234/p/14363641.html
 
 

 

 

汇总整理:

一、 数据库解决方案:

Round()、Convert()、Cast() 方法

https://www.cnblogs.com/hao-1234-1234/p/8574188.html 

三、 前端解决方案:

js中 Math.round()方法

https://www.cnblogs.com/hao-1234-1234/p/11150134.html

四、服务器端解决方案(C#)

Math.Round方法

https://www.cnblogs.com/hao-1234-1234/p/8668258.html

posted @ 2019-07-08 11:31  hao_1234_1234  阅读(51452)  评论(0编辑  收藏  举报