• js 取整,保留2位小数


    取整

    1 parseInt(string, radix)

    解析一个字符串,并返回一个整数
    当参数 radix 的值为 0,或没有设置该参数时,parseInt() 会根据 string 来判断数字的基数。
    如果 string 以 “0x” 开头,parseInt() 会把 string 的其余部分解析为十六进制的整数。
    如果 string 以 1 ~ 9 的数字开头,parseInt() 将把它解析为十进制的整数。

    parseInt(1.56) //1
    parseInt("1.56") // 1
    parseInt(0x12) // 18
    parseInt("0x12") // 18
    parseInt(-1.5) // -1
    
    • 1
    • 2
    • 3
    • 4
    • 5
    parseInt("abc") // NaN
    parseInt(12, 10) // 12
    parseInt(12.4, 10) // 12
    parseInt(12, 16) // 18
    parseInt(12.4, 16) // 18
    
    • 1
    • 2
    • 3
    • 4
    • 5
    2 Math.round(num)

    四舍五入取整,(5时向上取整

    Math.round(12) // 12
    Math.round("12") // 12
    
    Math.round(12.4) // 12
    Math.round(12.5) // 13
    Math.round("12.5") // 13
    
    Math.round(-12.5) //-12
    Math.round(-12.6) // -13
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    3 Math.ceil(num)

    向上取整

    Math.ceil(12) // 12
    Math.ceil("12") // 12
    
    Math.ceil(12.4) // 13
    Math.ceil(12.5) // 13
    Math.ceil("12.5") // 13
    
    Math.ceil(-12.5) // -12
    Math.ceil(-12.6) // -12
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    4 Math.floor

    向下取整

    Math.floor(12) // 12
    Math.floor("12") // 12
    
    Math.floor(12.4) // 12
    Math.floor(12.5) //12
    Math.floor("12.5") // 12
    
    Math.floor(-12.5) // -13
    Math.floor(-12.6) // -13
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    保留2位小数

    1 num.toFixed(x)

    把数字转换为字符串,结果的小数点后有指定位数的数字,四舍五入

    (1.55555).toFixed(2)   // '1.56'
    (1.5).toFixed(2)   // '1.50'
    
    • 1
    • 2
    2 借用Math.floor()/Math.round
    Math.floor(1.55555 * 100) / 100   // 1.55
    Math.floor(1.5 * 100) / 100   // 1.5
    
    Math.round(1.55555 * 100) / 100  //1.56
    Math.round(1.5 * 100) / 100   //1.5
    
    • 1
    • 2
    • 3
    • 4
    • 5
    3 借用字符串匹配
    Number((1.55555).toString().match(/^\d+(?:\.\d{0,2})?/))   // 1.55
    Number((1.5).toString().match(/^\d+(?:\.\d{0,2})?/))   // 1.5
    
    • 1
    • 2

    ^:匹配输入字符串的开始位置
    \d:匹配一个数字字符
    +:匹配前面的子表达式一次或多次
    (pattern):匹配 pattern 并获取这一匹配。所获取的匹配可以从产生的 Matches 集合得到
    (?:pattern):匹配 pattern 但不获取匹配结果,也就是说这是一个非获取匹配,不进行存储供以后使用。
    \.:匹配小数点
    {n,m}:最少匹配 n 次且最多匹配 m 次,在逗号和两个数之间不能有空格
    \d{n,m}:最少匹配 n 次最多匹配 m 次个数字字符
    ?:匹配前面的子表达式零次或一次

    附:"1.55555".match(/^\d+(\.\d{0,2})?/)会有两个结果,1.55.55

  • 相关阅读:
    这些阻碍程序员升职加薪的行为,你中招了几个?
    Linus Torvalds:最庆幸的是 30 年后,Linux 不是一个“死”项目
    信号稳定,性能卓越!德思特礁鲨系列MiMo天线正式发布!
    ES6闭包
    【Antd】InputNumber 只能输入整数
    Unity Quaternion接口API的常用方法解析_unity基础开发教程
    leetcode 57. 插入区间
    1529_AURIX_TriCore内核架构之编程模型
    八数码问题
    复习计算机网络——第二章习题记录
  • 原文地址:https://blog.csdn.net/weixin_43915401/article/details/127771240