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
  • 相关阅读:
    charindex使用一个异常记录思考
    真的有命运吗?
    《职道》序言:走向成功从职场细节开始
    迷人的笑容
    导致sql ce数据上传(采用push方法)不成功常见问题
    转篇文章,扫扫盲 《主流数据仓库产品对比分析》
    (转贴)JIRA安装和破解,随便看看吧
    Eclipse快捷键大全(转贴)
    没事在中移动MM商场做了2个应用,分别是运动专家和趣味闹钟
    免费实用微软系统工具集推荐(转)
  • 原文地址:https://www.cnblogs.com/xihe/p/6138606.html
Copyright © 2011-2022 走看看