[JavaScript]数字取小数点后固定位数

2016-03-03  本文已影响58人  lyn0130

object.toFixed([n])

  1. 舍弃规则为<code>四舍五入</code>
  2. object必须为数字,若为字符串会报异常<code>Uncaught TypeError: test.toFixed is not a function</code>
    <pre>
    var test = "100";
    test.toFixed(1);
    </pre>
  3. 若参数为空,默认位数为0
    <pre>
    var test = "100";
    test = parseInt(test);
    test.toFixed();
    console.log(test);
    </pre>
    结果为:<code>100</code>
  4. 参数范围为[0, 20],若超出范围为会报异常<code>Uncaught RangeError: toFixed() digits argument must be between 0 and 20</code>
    <pre>
    var test = "100";
    test = parseInt(test);
    test.toFixed(21);
    console.log(test);
    </pre>
上一篇 下一篇

猜你喜欢

热点阅读