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()执行向下舍入,即它总是将数值向下舍入为最接近的整数;一律舍去,仅保留整数

  • 相关阅读:
    vue 学习
    vue如何新建一个项目
    Java入门之流程控制语句
    Java 入门之数据类型转换、运算符、方法
    Java 入门 常量,变量
    Java 开发工具IntelliJ IDEA
    Java 前言&开发环境搭建
    Java 学习
    装饰器模式
    springcloud 的学习(五) 路由网关
  • 原文地址:https://www.cnblogs.com/kangby/p/8269356.html
Copyright © 2011-2022 走看看