前端小数点处理

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"
相关推荐
yugi987838几秒前
PNCC(Power-Normalized Cepstral Coefficients)— MATLAB 实现
开发语言·人工智能·matlab
甲维斯2 分钟前
GLM5.2超过Opus4.8Think,全球第二了!
前端·人工智能·ai编程
大黄说说3 分钟前
C++20 协程从入门到网络服务
开发语言
你是个什么橙4 分钟前
Python入门学习2:Python 基础语法全解析——从代码结构到输入输出
开发语言·python·学习
by————组态5 分钟前
Ricon组态系统 - 新一代Web可视化组态平台
前端·后端·物联网·架构·组态·组态软件
JieE2125 分钟前
手把手带你用纯 CSS 实现一个 3D 旋转魔方,这些前端基础你能打几分?
前端·css·html
小白学大数据7 分钟前
Python + 大模型行业资讯自动化摘要流水线完整工程实现方案
开发语言·python·自动化
何以解忧,唯有..15 分钟前
Go语言中的const:常量声明与iota枚举详解
java·开发语言·golang
lichenyang45318 分钟前
鸿蒙 Web 容器(二):H5 和 ArkTS 说话前,先定一份「协议」
前端
JYeontu21 分钟前
开箱流水加载动画
前端·javascript·css