前端小数点处理

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"
相关推荐
HashTang6 分钟前
Claude Code 源码中 REPL.tsx 深度解析:一个 5005 行 React 组件的架构启示
前端·后端·ai编程
不会写DN24 分钟前
PHP 中的文件读写与上传
android·开发语言·php
wendycwb1 小时前
前端城市地址根据最后一级倒推,获取各层级id的方法
前端·vue.js·typescript
LuckyTHP1 小时前
迁移shibboleth java获取shibboleth用户信息
java·开发语言
客卿1231 小时前
数论===质数统计(暴力法,)
java·开发语言
Σίσυφος19001 小时前
C++ 多肽经典面试题
开发语言·c++·面试
终端鹿1 小时前
Vue3 模板引用 (ref):操作 DOM 与子组件实例 从入门到精通
前端·javascript·vue.js
千寻girling1 小时前
不知道 Java 全栈 + AI 编程有没有搞头 ?
前端·人工智能·后端
csdn_aspnet2 小时前
C# 求n边凸多边形的对角线数量(Find number of diagonals in n sided convex polygon)
开发语言·算法·c#
小码哥_常2 小时前
Android开发:精准捕获应用的前后台行踪
前端