zoukankan      html  css  js  c++  java
  • js 保留2位小数

    一、四舍五入法

    1.jquery 小数计算保持精度,同时保留两位数

    toFixed() 方法可把 Number 四舍五入为指定小数位数的数字。

    var num = 1.45698;
    num = parseFloat(num.tofixed(2));

    注意toFixed方法返回的结果是字符串类型

    2.toFixed 四舍五入遇到坑。

    1.235.toFixed(2) = 1.23
    1.2350001.toFixed(2) = 1.24

    3.

    //四舍五入法
    Number.prototype.toRound = function (num) {
    return Math.round(this * Math.pow(10, num)) / Math.pow(10, num);
    };

    Math.round()执行标准舍入,即它总是将数值四舍五入为最接近的整数。

    pow() 方法可返回 x 的 y 次幂的值。

    document.write(Math.pow(1,10) + "<br />")   //1
    document.write(Math.pow(2,3) + "<br />")    //8

    round() 方法可把一个数字舍入为最接近的整数。返回与 x 最接近的整数。进行四舍五入 

    document.write(Math.round(0.50) + "<br />")   //1
    document.write(Math.round(0.49) + "<br />")   //0
    document.write(Math.round(-4.40) + "<br />" )   //-4

    二、进一法

    Number.prototype.toCeil = function (num) {
    return Math.ceil(this * Math.pow(10, num)) / Math.pow(10, num);
    };

    Math.ceil()执行向上舍入,即它总是将数值向上舍入为最接近的整数;将小数部分一律向整数部分进位

    三、去尾法

    Number.prototype.toFloor = function (num) {
    return Math.floor(this * Math.pow(10, num)) / Math.pow(10, num);
    };

    Math.floor()执行向下舍入,即它总是将数值向下舍入为最接近的整数;一律舍去,仅保留整数

  • 相关阅读:
    格式化数字保留N位小数
    listbox美化
    501 Not Implemented:服务器不支持实现请求所需要的功能。例如,客户发出了一个服务器不支持的PUT请求。
    截透明
    CASE WHEN
    c# HttpWebRequest与HttpWebResponse 绝技
    提取网页中的超链接(C#)
    转sqlhelp
    IIS创建虚拟目录
    一次重构的过程
  • 原文地址:https://www.cnblogs.com/kangby/p/8269356.html
Copyright © 2011-2022 走看看