将间隔四舍五入为数字,逐步定义 [英] Round double to number in interval, defining by step

查看:90
本文介绍了将间隔四舍五入为数字,逐步定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些抽象的双间隔,由fe定义:

I have some abstract double interval, defining by step f.e.:

0.0,0.1,0.2,0.3,0.4,0.5,0.6, 0.7、0.8、0.9、1.0-其中间隔== 0.1

0.0、0.25、0.5、0.75、1.0 -其中间隔== 0.25

0.0,0.5,1.0-其中间隔== 0.5

根据间隔,Java是否有某种工具可以舍入一些双精度至最接近的数字? fe:

Does Java have some instrument to "round" some double to closest number, according to interval? f.e:

0.511111-第一种情况下为0.5

0.599999-到0.6 在第一种情况下

0.511111-到0.5 在第二种情况下

0.599999-到0.5 在第二种情况下

0.711111-第二种情况下为0.75

0.744444-在第三种情况下为0.5

0.755555-在第三种情况下为1.0

0.92222-在第三种情况下为1.0

推荐答案

Java具有可以将数字四舍五入到小数点后n位的工具,请参见如何在Java中将数字四舍五入到小数点后n位。要舍入到指定的任何时间间隔,可能必须手动使用 Math.round

Java has instruments which can round numbers to n decimal places, see How to round a number to n decimal places in Java. For rounding to any interval you specified, you may have to manually use Math.round.

公式:

给出间隔 r 和双值 x 取整,一个简单的公式是:

Given an interval r and a double value x to round, a simple formula is:


  • x_rounded = Math.round(x / r )* r;

  • x_rounded = Math.round(x/r)*r;

示例:

double x = 0.59999;
double r = 0.25; // Quarters
x = Math.round(x/r)*r;
System.out.println(x); // Result is 0.5

double x = 0.59999;
double r = 0.1; // Tenths
x = Math.round(x/r)*r;
System.out.println(x); // Result is approximately 0.6

double x = 0.31421;
double r = 0.125; // Eighths
x = Math.round(x/r)*r;
System.out.println(x); // Result is exactly 0.375

证明:


  • 间隔 r 可以看作是小数单位的值。


    • r = 0.25 时,小数单位为四分之一。

    • The interval r can be thought as the value of a fractional unit.
      • When r = 0.25, the fractional unit is a quarter.

      • x = 0.75 时, r = 0.25 x / r == 3 ,因为 x 包含三个分数单位,即四分之一。 x / r 代表季度数。

      • When x = 0.75, r = 0.25, x/r == 3, because x contains three fractional unit, which is the quarter. x/r represents the number of quarters.

      • 对于 x = 0.7,r = 0.25 ,我们有 x / r = 2.8 ,代表2.8个季度。 Math.round(x / r)因此将值四舍五入到最近的四分之一季度,即3个季度。

      • For x = 0.7, r = 0.25, we have x/r = 2.8, representing 2.8 quarters. Math.round(x/r) therefore rounds the value to the nearest quarter, 3 quarters.

      • 对于 x = 0.7,r = 0.25 Math.round( x / r)代表3个季度。必须将其乘以 r = 0.25 才能得出 x 的舍入值。

      • For x = 0.7, r = 0.25, Math.round(x/r) represents 3 quarters. It has to be multiplied by r=0.25 to get the rounded value of x.

      这篇关于将间隔四舍五入为数字,逐步定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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