使用javascript四舍五入小数
我需要使用 javascript 将小数值四舍五入到小数位。
例如:
16.181 to 16.18
16.184 to 16.18
16.185 to 16.19
16.187 to 16.19
我找到了一些答案,但大多数都没有将 16.185 舍入到 16.19。
I need to round off the decimal value to decimal places using javascript.
Ex,:
16.181 to 16.18
16.184 to 16.18
16.185 to 16.19
16.187 to 16.19
I have found some answers, but most of them do not round off 16.185 to 16.19..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
如果你的值是,例如 16.199,正常回合将返回 16.2...但使用此方法,你也会得到最后 0,所以你会看到 16.20!但请记住,该值将以字符串形式返回。如果你想将它用于进一步的操作,你必须解析它:)
现在作为函数:
If your value is, for example 16.199 normal round will return 16.2... but with this method youll get last 0 too, so you see 16.20! But keep in mind that the value will returned as string. If you want to use it for further operations, you have to parsefloat it :)
And now as function:
感谢@ayk的回答,我将你的函数修改为:
只需添加“ *1 ”
因为对于你的,正如你所写,16.2 变成 16.20
我不需要后面的零。
Thanks @ayk for your answer, I modified your function into this :
just add " *1 "
because with yours, as you wrote, 16.2 becomes 16.20
and I don't need the zero in the back.
使用
-这在我的情况下可以完美工作,希望它能 100% 工作
Use-
This will work perfectly in my case ,hope it will work 100%
您可以尝试一个更简单的功能...
它是如何工作的?
该位置可以是 10、100、1000、10000 等。反之则为 0.1、0.01、0.001,以此类推。假设您的数字是 16.185,您的位置是 100。它要做的第一件事就是将数字乘以位置,即 1618.5。用 Math.round 四舍五入得到 1619。除以位数得到 16.19。那里。
顺便说一句,今天不用担心 0.5 的问题,它已经解决了。但以防万一,请将 Math.round(number * place) 更改为 Math.round(number * place + 0.1)。
You COULD try a simpler function...
How does it work?
The place can be 10, 100, 1000, 10000, and so on. The reverse will be 0.1, 0.01, 0.001, and so on. Let's say your number is 16.185, and your place is 100. The first thing it'll do is to multiply the number by the place, which is 1618.5. Rounding it off by Math.round will result in 1619. Dividing by the place gives us 16.19. There.
By the way, no need to worry about the .5 problem today, it's kinda fixed. But just in case it isn't, change Math.round(number * place) to Math.round(number * place + 0.1).
您正在使用的代码是正确的。但是要获得所需的结果,请从代码中删除.tofixed(numofdec)。
函数:
函数格式名称(mynum,numofdec){
希望它以某种方式帮助您:)
The code you are using for rounding off is correct. But to get the desired result please remove the .toFixed(numOfDec) from the code.
The function:
function formatNumber(myNum, numOfDec) {
Hope it helps you in some way :)
[编辑]
此代码不适用于 18.185 这样的值,因为 18.185 * Math.pow(10,2) 正在计算为 1818.4999999999997
示例:
1234.5678 --> 2 位小数 --> 1234.57
[EDIT]
This code does not work for a value like 18.185, as 18.185 * Math.pow(10,2) is being evaluated to 1818.4999999999997
Example:
1234.5678 --> 2 decimal places --> 1234.57