zoukankan      html  css  js  c++  java
  • JS原始类型:数值的运用技巧

    保留特定位数的小数

    有一些题目常常要求格式化数值,:比如保存几位小数等等。
    1.使用Number.prototype.toFixed() 原生方法。该方法的参数为要保存的小数位数,有效范围为0到20,超出这个范围将抛出RangeError错误。此方法以四舍五入的方式处理多出的小数。
    语法为:

    numObj.toFixed([digits])

    例子:

    var temp = 3.141592653;
    console.log(temp.toFixed(2));
    //输出为3.14
    //此方法以四舍五入的方式处理多出的小数。
    console.log(temp.toFixed(4));
    //输出为3.1416

    如需要将末尾多余的0舍去,可以这样写:

    var temp1 = 3.0596;
    console.log(temp1.toFixed(3)*1000/1000);
    //输出为3.06

    2.使用Math.round() 方法。

    var temp2 = 2.17698;
    console.log(Math.round(temp2*1000)/1000);
    //输出为2.177
    //试一试能不能去掉末尾多余的0
    var temp2 = 2.17998;
    console.log(Math.round(temp2*1000)/1000);
    //输出为2.18,可以去掉末尾多余的0

    Math.ceil()也适用于这种写法。

    3.使用字符串对象的substr方法。

    var temp3 = 1.0836;
    var res = String(temp3).substr(0,String(temp3).indexOf('.')+3)
    console.log(Number(res))
    //输出为1.08

    进制相互转换

    其他进制转为十进制使用parseInt()方法:
    Number.parseInt() 方法可以根据给定的进制数把一个字符串解析成整数,语法为:

    Number.parseInt(string[, radix])

    例子:

    var res = Number.parseInt('123',16);
    console.log(res);
    //输出为291,也即十六进制的123转为十进制为291
    var res = Number.parseInt('123',8);
    console.log(res);
    //输出为83

    **注意:**parseFloat()并无这样的特性,该方法只是纯粹的转化浮点数的功能

    十进制转为其他进制:Number对象部署了单独toString()方法,可以接受一个参数,表示将一个数字转化为某个进制的字符串。

    (10).toString() //输出为‘10’
    (10).toString(2)//输出为‘1010’
    (10).toString(8)//输出为‘12’
    (10).toString(16)//输出为‘a’

    注意该方法改变了数据类型

    console.log(typeof (10).toString(2))//输出为string
  • 相关阅读:
    线段树入门总结
    从零基础学三分查找
    Codeforces Beta Round #1 A,B,C
    isupper()函数
    matlab字符串操作总结
    hdu 4873 ZCC Loves Intersection(大数+概率)
    设计模式入门之桥接模式Bridge
    有关UIWebView的SSL总结
    vmware虚拟机上linux操作系统进行tty1~tty6切换方法和具体步骤
    Python BeautifulSoup4 使用指南
  • 原文地址:https://www.cnblogs.com/xihe/p/6138606.html
Copyright © 2011-2022 走看看