小程序保留2位小数据,不四舍五入

方法1: parseInt + toFixed

复制代码
/*
* 保留2位小数,不四舍五入
* 5.992550 =>5.99 , 2 => 2.00
* */
const toFixed2Decimal = (value) => {
  return (parseInt(value*100)/100).toFixed(2)
}
console.log(587.67*100)
console.log(toFixed2Decimal(587.67))
console.log(toFixed2Decimal(-0.1123456))
console.log(toFixed2Decimal(-1))
console.log(toFixed2Decimal('-12.999'))
console.log(toFixed2Decimal('-12.99999'))
module.exports = {
  toFixed2Decimal: toFixed2Decimal
}

输出 :

58766.99999999999
587.66

-0.11

-1.00

-12.99

-12.99

有问题: 587.67 转换之后 587.66

方法2:Math.floor + tofixed

复制代码
const toFixed2Decimal = (value) => {
  return (Math.floor(value*100)/100).toFixed(2)
}

console.log(toFixed2Decimal(-0.1123456))
console.log(toFixed2Decimal(-1))
console.log(toFixed2Decimal('-12.999'))
console.log(toFixed2Decimal('-12.99999'))

输出:

-0.12

-1.00
-13.00
-13.00

有问题-12.99 得出-13.00

想哭啊。2种方法出来的钱的值都不对。

相关推荐
支撑前端荣耀4 分钟前
从零实现前端监控告警系统:SMTP + Node.js + 个人邮箱 完整免费方案
前端·javascript·面试
重铸码农荣光8 分钟前
🎯 从零搭建一个 React Todo 应用:父子通信、状态管理与本地持久化全解析!
前端·react.js·架构
用户4099322502128 分钟前
Vue3 v-if与v-show:销毁还是隐藏,如何抉择?
前端·vue.js·后端
Mr_chiu9 分钟前
🚀 效率暴增!Vue.js开发必知的15个神级提效工具
前端
shanLion9 分钟前
Vite项目中process报红问题的深层原因与解决方案
前端·javascript
烟袅11 分钟前
从零构建一个待办事项应用:一次关于组件化与状态管理的深度思考
前端·javascript·react.js
前端小万14 分钟前
草稿
前端
闲云一鹤16 分钟前
将地图上的 poi 点位导出为 excel,并转换为 shp 文件
前端·cesium
岁月宁静1 小时前
MasterGo AI 实战教程:10分钟生成网页设计图(附案例演示)
前端·aigc·视觉设计
狗头大军之江苏分军1 小时前
快手12·22事故原因的合理猜测
前端·后端