• 如何实现parseFloat保留小数点后2位


    Number.toPrecision(2);
    function toPrecision ( [precision : Number] ) : String
    参数 
    precision 
    可选项。有效位数。值必须介于 1 - 21 之间(含 1 和 21)。


    备注 
    对于以指数记数法表示的数字,将返回小数点后的 precision - 1 位数字。对于以定点记数法表示的数字,将返回 precision 位有效位数。
    如果没有提供参数 precision 或者它为 undefined,则将转而调用 toString 方法。

    要求 
    版本 5.5

     

     

    应用于:

    Number 对象


    以下是网上其它信息
    1:

    t.toFixed(2);

    2:

    t=Math.round(t*100)/100; 
    alert(t);

    3:

    <script> a=3.4534134; alert(parseInt(a*100)/100) </script>

    补充:

    这个方法是在一个例子中看到的,我测试了一下是小数点后四舍五入的功能

    例如,5.05---->toFixed(1) 5.1

    5.056-------->toFixed(2) 5.06

    但是用到0.056时就出现问题了toFixed(1)的结果是0.0

    有点奇怪的答案

    下面的脚本是重写了toFixed(),这样0.056就可以转化到0.1了

    Number.prototype.toFixed=function(len)
    {
    var add = 0;
    var s,temp;
    var s1 = this + "";
    var start = s1.indexOf(".");
    if(s1.substr(start+len+1,1)>=5)add=1;
    var temp = Math.pow(10,len);
    s = Math.floor(this * temp) + add;
    return s/temp;
    }

  • 相关阅读:
    Oracle8i安装问题
    c# 值類型與引用類型
    C# String轉成FontStyle
    为GridView“删除”列添加确认对话框(轉)
    c# 輸出字符編碼
    了解C#命名空間
    Asp.Net安全控件說明
    C# 数组学习
    c# 方法的參數傳遞機制
    c# 得到所有XmlElement節點的值
  • 原文地址:https://www.cnblogs.com/shiyh/p/7145470.html
Copyright © 2020-2023  润新知