JS-数字处理

小数相加

console.log(0.1+0.2); // 0.30000000000000004

最大的数 + 1 得到的结果就是...[isFinite参考地址]

var result = Number.MAX_VALUE + 1;
alert(isFinite(result)); // false

NaN 的判断

    alert(NaN == NaN);       //false
    alert(isNaN(NaN));       //true
    alert(isNaN(10));        //false – 10 is a number
    alert(isNaN("10"));      //false – can be converted to number 10
    alert(isNaN("blue"));    //true – cannot be converted to a number
    alert(isNaN(true));      //false – can be converted to number 1

数字的强制转换

    var num1 = Number("Hello world!");  //NaN
    var num2 = Number("");              //0
    var num3 = Number("000011");        //11
    var num4 = Number(true);            //1

转换函数[ parseInt 默认是转换为 十进制 的] - parseFloat 类似

    var num1 = parseInt("1234blue");    //1234
    var num2 = parseInt("");            //NaN
    var num3 = parseInt("0xA");         //10 - hexadecimal
    var num4 = parseInt(22.5);          //22
    var num5 = parseInt("70");          //70 - decimal
    var num6 = parseInt("0xf");         //15 – hexadecimal
    var num1 = parseInt("AF", 16);        //175 - 指定进制,转换成功
    var num2 = parseInt("AF");            //NaN - 未指定进制,默认十进制,转换失败
    var num1 = parseInt("10", 2);         //2 – parsed as binary
    var num2 = parseInt("10", 8);         //8 – parsed as octal
    var num3 = parseInt("10", 10);        //10 – parsed as decimal
    var num4 = parseInt("10", 16);        //16 – parsed as hexadecimal

    var num1 = parseFloat("1234blue");    //1234 - integer
    var num2 = parseFloat("0xA");         //0
    var num3 = parseFloat("22.5");        //22.5
    var num4 = parseFloat("22.34.5");     //22.34
    var num5 = parseFloat("0908.5");      //908.5
    var num6 = parseFloat("3.125e7");     //31250000

数字的类型、转换、小数位数、科学计数法

    var numberObject = new Number(10);
    var numberValue = 99;
    //toString() 指定进制
    alert(numberObject.toString());       //"10"
    alert(numberObject.toString(2));      //"1010"
    alert(numberObject.toString(8));      //"12"
    alert(numberObject.toString(10));     //"10"
    alert(numberObject.toString(16));     //"a"
    //toFixed() 小数位数
    alert(numberObject.toFixed(2));    //outputs "10.00"
    // 科学计数法
    numberObject = new Number(99);
    alert(numberObject.toPrecision(1));    //"1e+2"
    alert(numberObject.toPrecision(2));    //"99"
    alert(numberObject.toPrecision(3));    //"99.0"
    // 类型判断
    alert(typeof numberObject);   //object
    alert(typeof numberValue);    //number
    alert(numberObject instanceof Number);  //true
    alert(numberValue instanceof Number);   //false