zoukankan      html  css  js  c++  java
  • 怎么解决javascript小数相减会出现一长串的小数位数?

    例如parseFloat(11.3-10.1) 或者直接11.3-10.1    出来的结果是1.200000000000001

    最终只能取个相对理想的方法,但是还是没有达到预期希望的那样把

    就是在你相减完之后,进行小数点的取舍

    parseFloat(11.3-10.1).toFixed(1)

    例外js里面的字符串转换为数字的话,可以直接通过*1来实现

    例如:parseFloat(“1.27”*1 - “1.11”*1).toFixed(2)

    论坛里一个牛人给出的总结方法:

    String.prototype.toFloat=Number.prototype.toFloat=function(decimalPlace,isRoundUp){

    /// <summary>
    /// String,Number原型扩展:保留指定的小数位数[可选择是否使用四舍五入]
    /// </summary>
    /// <param name="decimalPlace">需要保留的小数位</param>
    /// <param name="isRoundUp">是否是舍五入[可选项:默认true]</param>
    /// <returns>数据类型:Number(浮点数)</returns>

    decimalPlace = decimalPlace || 0,
    isRoundUp = Object.prototype.toString.call(isRoundUp).match(/^[objects(.*)]$/)[1].toLowerCase()=='boolean' ? isRoundUp : !0;
    try{
    var res = isRoundUp
    ? (this*1).toFixed(decimalPlace)
    : this.toString().replace(new RegExp("([0-9]+.[0-9]{"+decimalPlace+"})[0-9]*","g"),"$1");
    return isNaN(res*1) ? this: res;
    }catch(e){
    return isNaN(this*1) ? this : this*1;//防止小数位数字越界
    }
    }
    alert(parseFloat(11.3-10.1222222).toFloat(2,!0))

  • 相关阅读:
    Lucene基础排序算法改进
    大数据量的过滤 (用于爬虫,蜘蛛) Bloom Filter 布隆过滤器
    往空间,博客里添加音乐播放器
    汇编随笔
    一个女程序员的故事(酷壳陈皓)
    cmd 命令之删除整个文件夹
    亿度空间
    用wubi.exe安装ubuntu下载速度很慢怎么办?
    qtm第一次
    copy的妙用
  • 原文地址:https://www.cnblogs.com/wenghaowen/p/3185998.html
Copyright © 2011-2022 走看看