Skip to content

解决 toFixed 保留小数会 四舍五入问题 #267

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
smileyby opened this issue Mar 20, 2023 · 0 comments
Open

解决 toFixed 保留小数会 四舍五入问题 #267

smileyby opened this issue Mar 20, 2023 · 0 comments
Labels

Comments

@smileyby
Copy link
Owner

smileyby commented Mar 20, 2023

toFxied() 方法,将数字保留指定位数后,返回保留位数的字符串
2.45.toFixed(1) => '2.5'
2.44.toFixed(1) => '2.4'

使用 parseInt 解决保留小数部分时四舍五入的情况

  1. 将原数值 num 扩大 10^n 倍 (num = num * Math.pow(10, n)),n为要保留的小数位数
  2. 将放大后的数值取整,并除以放大的倍数 parseInt(num) / Math.pow(10, n)
  3. 最后得到的数值就是原数值,保留 n 位小数没有四舍五入的数值
@smileyby smileyby added the JavaScript ☀️ JavaScript label Mar 20, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant