jQuery 将小数四舍五入为 0.49 或 0.99
我正在尝试弄清楚如何将小数四舍五入为 0.49 或 0.99。
我找到了 toFixed(2) 函数,但不确定如何向上或向下舍入。
基本上需要达到最接近的价格点,例如 X.55 将下降到 X.49,X.84 将上升到 X.99。
I'm trying to work out how to round a decimal to .49 or .99.
I have found the toFixed(2)
function, but not sure how to round up or down.
Basically need to get to the closest price point, so for example X.55 would go down to X.49 and X.84 would go up to X.99.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这不需要 jQuery,但可以使用纯 JavaScript 来完成:
请注意,还要考虑数字四舍五入为 0 (
price
> 0.25) 的情况,因为在这种情况下会产生 -0.01 。This doesn’t require jQuery but can be done with plain JavaScript:
Note to also consider the case where the number would get rounded to 0 (
price
> 0.25) as that would yield -0.01 in this case.如果每次 jQuery 让事情变得比他们需要的更加迟钝时我都能得到一美元......
If I had a dollar for every time jQuery made things more obtuse than they needed to be...
我认为您无法四舍五入/固定为特定数字,您需要检查/计算该值,这可能意味着:四舍五入然后减去 1 或四舍五入并减去 51。
I thing you cant round/fix to a specific number, you will need to check/caclulate the value, which could mean: rounding up then subtracting 1 or rounding up and subtracting 51.
这不需要 jQuery。你只需要 JavaScript 中的 Math 类,四舍五入还需要一些额外的减法,因为四舍五入会给出最接近的小数
This does not require jQuery. You just need Math class from javascript also rounding off will require some addtional subtraction since rounding will give nearest decimal
稍微编辑一下 aroth 的答案,以便我们还需要四舍五入到最近的 5 乘法值
Editing aroth's answer a little bit in order to lets say we also need to round to nearest 5 multiply value