Javascript:向上和向下舍入到最接近的5,然后找到一个共同点 [英] Javascript: Round up and down to the nearest 5, then find a common denominator

查看:82
本文介绍了Javascript:向上和向下舍入到最接近的5,然后找到一个共同点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来向上和向下到达nearerst 5,然后找到这两个数字的一​​个很好的共同点。
我需要它来表示图表上的y-skale标题。

iam looking for a way to Round up AND down to the nearerst 5 and then find a great common denominator of the two numbers. I need it for the caption of a y-skale on a chart.

这是我到目前为止的代码:

This is my code so far:

function toN5( x ) {
    var i = 1;
    while( x >= 100 ) {
        x/=10; 
        i*=10;
    }
    var remainder = x % 5;
    var distance_to_5 = (5 - remainder) % 5;
    return (x + distance_to_5) * i;
}

目标是这样的:
最大值(圆形)最近的5)

The target is something like this: The maximal value (round up to the nearest 5)

1379.8 -> 1500

反之亦然 - 最小值(向下舍入到最接近的5)

And the other way round - minimal value (round down to the nearest 5)

41.8 -> 0

然后我想找到一个共同的分母,如250或500

Then i want to find a common denominator like 250 or 500


0 - > 250 - > 500 - > 750 - > 1000 - > 1250 - > 1500

0 -> 250 -> 500 -> 750 -> 1000 -> 1250 -> 1500

或:

0 -> 500 -> 1000 -> 1500

是不是可以这样做?非常感谢

Is ther a way to do something like that? Thanks a lot

推荐答案

如果你想将 x 舍入到最接近的500,你可以将它分开乘以500,将其四舍五入到最接近的整数,然后再将其乘以500:

If you wanted to round x to the nearest 500, you could divide it by 500, round it to the nearest integer, then multiply it by 500 again:

x_rounded = 500 * Math.round(x/500);

要将其四舍五入到最近的 y ,请用替换500 y

To round it to the nearest y, replace 500 with y:

x_rounded = 250 * Math.round(x/250);

这篇关于Javascript:向上和向下舍入到最接近的5,然后找到一个共同点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆