前端小数点处理

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"
相关推荐
qq_411262421 天前
短时间串口发送网络端怎么接收不到
开发语言·php
静谧空间1 天前
java登录验证码CaptchaConfig
java·开发语言
小高Baby@1 天前
session、cookie、Jwt-token
开发语言·后端·golang
咔咔一顿操作1 天前
轻量无依赖!autoviwe 页面自适应组件实战:从安装到源码深度解析
javascript·arcgis·npm·css3·html5
maplewen.1 天前
C++11 std::mutex
开发语言·c++
jiaguangqingpanda1 天前
Day37-20260205
java·开发语言
历程里程碑1 天前
21:重谈重定义理解一切皆“文件“及缓存区
linux·c语言·开发语言·数据结构·c++·算法·缓存
weixin_433179331 天前
Python - 软件对象
开发语言·python
刘联其1 天前
.net也可以用Electron开发跨平台的桌面程序了
前端·javascript·electron
韩曙亮1 天前
【jQuery】jQuery 选择器 ④ ( jQuery 筛选方法 | 方法分类场景 - 向下找后代、向上找祖先、同级找兄弟、范围限定查找 )
前端·javascript·jquery·jquery筛选方法