前端小数点处理

1.Math.floor

Math.floor() 函数总是返回小于等于一个给定数字的最大整数。

javascript 复制代码
console.log(Math.floor(5.95));
// Expected output: 5

console.log(Math.floor(5.05));
// Expected output: 5

console.log(Math.floor(5));
// Expected output: 5

console.log(Math.floor(-5.05));
// Expected output: -6

2.Math.ceil

Math.ceil() 静态方法总是向上舍入,并返回大于等于给定数字的最小整数。

javascript 复制代码
console.log(Math.ceil(0.95));
// Expected output: 1

console.log(Math.ceil(4));
// Expected output: 4

console.log(Math.ceil(7.004));
// Expected output: 8

console.log(Math.ceil(-7.004));
// Expected output: -7

3.Math.round

Math.round() 函数返回一个数字四舍五入后最接近的整数。

javascript 复制代码
let x
x = Math.round(20.49); //20
x = Math.round(20.5); //21
x = Math.round(-20.5); //-20
x = Math.round(-20.51); //-21

4.Number.prototype.toFixed()

Number 值的 toFixed() 方法使用定点表示法来格式化该数值。

注意:如果不是number,会抛出异常

javascript 复制代码
function financial(x) {
  return Number.parseFloat(x).toFixed(2);
}

console.log(financial(123.456));
// Expected output: "123.46"

console.log(financial(0.004));
// Expected output: "0.00"

console.log(financial("1.23e+5"));
// Expected output: "123000.00"
相关推荐
阿俊-全栈开发2 小时前
LikeShop 单商户SaaS商城分销模块二开:佣金计算与结算逻辑实现
java·开发语言·微服务·likeshop·likeshop开源商城·likeshop多商户
奕鼎竜瑆4 小时前
Solid 前端响应式开发从零到精通
前端·人工智能
动恰客流统计4 小时前
景区客流统计怎么做?兼顾管控与运营的实施方案解析
大数据·前端·人工智能
派小心.5 小时前
A/B测试工具免费版够用吗?
前端·数据分析
m0_380743875 小时前
C++中的freopen的用法实例详解
开发语言·c++
前端snow5 小时前
ai agent --- redis 缓存
前端
Escalating_xu5 小时前
【Python】基础语法(1):常量、变量、类型、输入输出与运算符
开发语言·python
jimy16 小时前
polymorph.cpp里面的“析构函数、智能指针”问题
开发语言·c++
m0_380743876 小时前
PHP 8.3 缓存清除不生效怎么排查
开发语言·php
duanshu_6 小时前
官网表单与下载异常怎么排查?五个环节定位故障
前端·自动化·flyweight