小程序保留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种方法出来的钱的值都不对。

相关推荐
我不吃饼干9 天前
鸽了六年的某大厂面试题:你会手写一个模板引擎吗?
前端·javascript·面试
源码_V_saaskw9 天前
宇鹿家政服务系统小程序ThinkPHP+UniApp
微信小程序·小程序·uni-app·微信公众平台
涵信9 天前
第一节 布局与盒模型-Flex与Grid布局对比
前端·css
我不吃饼干9 天前
鸽了六年的某大厂面试题:手写 Vue 模板编译(解析篇)
前端·javascript·面试
前端fighter9 天前
为什么需要dependencies 与 devDependencies
前端·javascript·面试
满楼、9 天前
el-cascader 设置可以手动输入也可以下拉选择
javascript·vue.js·elementui
veminhe9 天前
HTML5 浏览器支持
前端·html·html5
前端fighter9 天前
Vuex 与 Pinia:全面解析现代 Vue 状态管理的进化之路
前端·vue.js·面试
嘉琪0019 天前
2025——js 面试题
开发语言·javascript·ecmascript
snow@li9 天前
vue3-ts-qrcode :安装及使用记录 / 配置项 / 效果展示
前端·javascript·vue.js