JavaScript/Number

来自康健生活

引言

在内部被表示为 64 位的浮点数。且没有分离整数类型。

1 === 1.0
true

整数

浮点数

指数

console.log(Number.isFinite(10), Number.isFinite(-Infinity), Number.isFinite('10')); // 检测数字是否为有限数字
console.log(Number.isNaN(10), Number.isNaN(NaN), Number.isNaN('10')); // 检测是否为 NaN
console.log(Number.parseInt(10.123), Number.parseInt(void 1), Number.parseInt('10.456')); // 返回整数
console.log(Number.parseFloat('123.45#abc'), Number.parseFloat(void 1), Number.parseFloat('abc123.45')); // 返回浮点数
console.log(Number.isInteger(10), Number.isInteger(10.0), Number.isInteger('10.0')); // 判断是否为整数
console.log(Math.trunc('123.456')); // 去掉小数
console.log(Math.sign('10'), Math.sign(-10), Math.sign(0), Math.sign('-0'), Math.sign(void 1)); // 判断数字类型
true false false
false true false
10 NaN 10
123.45 NaN NaN
true true false
123
1 -1 0 -0 NaN

四舍五入

Math.round

Math.round(55.4355 * 100) / 100;
55.44

toFixed

舍入规则 Number.prototype.toFixed ( fractionDigits )[1]。

(new Number(100.345));
(new Number(100.345)).toFixed(2);
Number {100.345}
'100.34'

自定义

function fixed(num, digit) {
  if(Object.is(parseFloat(num), NaN)) {
    return console.log(`传入的值:${num}不是一个数字`);
  }
  num = parseFloat(num);
  return (Math.round((num + Number.EPSILON) * Math.pow(10, digit)) / Math.pow(10, digit)).toFixed(digit);
}
fixed(12.34567, 4);
'12.3457'

库

kind-of is-number big.js
bignumber.js decimal.js 示例
示例 示例 示例
  1. ↑ Ecma International.ECMAScript® 2015 Language Specification:Number.prototype.toFixed ( fractionDigits )[S]:2015