如何在Java中将数字舍入到n个小数位

时间:2008-09-30 16:01:35

标签: java decimal rounding digits

我想要的是一种将double转换为使用half-up方法进行舍入的字符串的方法 - 即如果要舍入的小数是5,则它总是向上舍入到前一个数字。这是大多数人在大多数情况下期望的标准方法。

我也希望只显示有效数字 - 即不应该有任何尾随零。

我知道这样做的一种方法是使用String.format方法:

String.format("%.5g%n", 0.912385);

返回:

0.91239

这很好,但是它总是显示带有5位小数的数字,即使它们不重要:

String.format("%.5g%n", 0.912300);

返回:

0.91230

另一种方法是使用DecimalFormatter

DecimalFormat df = new DecimalFormat("#.#####");
df.format(0.912385);

返回:

0.91238

然而,你可以看到这使用半均匀舍入。也就是说,如果前一个数字是偶数,它将向下舍入。我想要的是:

0.912385 -> 0.91239
0.912300 -> 0.9123

在Java中实现这一目标的最佳方法是什么?

35 个答案:

答案 0 :(得分:684)

使用setRoundingMode,明确设置RoundingMode以处理半偶数问题,然后使用格式模式获取所需的输出。

示例:

DecimalFormat df = new DecimalFormat("#.####");
df.setRoundingMode(RoundingMode.CEILING);
for (Number n : Arrays.asList(12, 123.12345, 0.23, 0.1, 2341234.212431324)) {
    Double d = n.doubleValue();
    System.out.println(df.format(d));
}

给出输出:

12
123.1235
0.23
0.1
2341234.2125

答案 1 :(得分:437)

假设valuedouble,您可以执行以下操作:

(double)Math.round(value * 100000d) / 100000d

这是5位精度。零的数量表示小数位数。

答案 2 :(得分:177)

new BigDecimal(String.valueOf(double)).setScale(yourScale, BigDecimal.ROUND_HALF_UP);

会给你一个BigDecimal。要从中获取字符串,只需调用BigDecimal的{​​{1}}方法或Java 5+的toString方法作为纯格式字符串。

示例程序:

toPlainString

答案 3 :(得分:108)

您也可以使用

DecimalFormat df = new DecimalFormat("#.00000");
df.format(0.912385);

确保你有0的结尾。

答案 4 :(得分:77)

正如其他人所说,正确的答案是使用DecimalFormatBigDecimal。浮点不会具有小数位,因此您不可能首先将其舍入/截断为特定数量的小数位。你必须使用十进制基数,这就是这两个类的作用。

我发布以下代码作为此线程中所有答案的反例 - 实际上遍布StackOverflow(以及其他地方)建议乘法,然后是截断,然后是除法。这种技术的拥护者有责任解释为什么以下代码在超过92%的情况下产生错误的输出。

public class RoundingCounterExample
{

    static float roundOff(float x, int position)
    {
        float a = x;
        double temp = Math.pow(10.0, position);
        a *= temp;
        a = Math.round(a);
        return (a / (float)temp);
    }

    public static void main(String[] args)
    {
        float a = roundOff(0.0009434f,3);
        System.out.println("a="+a+" (a % .001)="+(a % 0.001));
        int count = 0, errors = 0;
        for (double x = 0.0; x < 1; x += 0.0001)
        {
            count++;
            double d = x;
            int scale = 2;
            double factor = Math.pow(10, scale);
            d = Math.round(d * factor) / factor;
            if ((d % 0.01) != 0.0)
            {
                System.out.println(d + " " + (d % 0.01));
                errors++;
            }
        }
        System.out.println(count + " trials " + errors + " errors");
    }
}

该计划的输出:

10001 trials 9251 errors

编辑:为了解决下面的一些评论,我使用BigDecimalnew MathContext(16)对模数操作重新设置了测试循环的模数部分,如下所示:

public static void main(String[] args)
{
    int count = 0, errors = 0;
    int scale = 2;
    double factor = Math.pow(10, scale);
    MathContext mc = new MathContext(16, RoundingMode.DOWN);
    for (double x = 0.0; x < 1; x += 0.0001)
    {
        count++;
        double d = x;
        d = Math.round(d * factor) / factor;
        BigDecimal bd = new BigDecimal(d, mc);
        bd = bd.remainder(new BigDecimal("0.01"), mc);
        if (bd.multiply(BigDecimal.valueOf(100)).remainder(BigDecimal.ONE, mc).compareTo(BigDecimal.ZERO) != 0)
        {
            System.out.println(d + " " + bd);
            errors++;
        }
    }
    System.out.println(count + " trials " + errors + " errors");
}

结果:

10001 trials 4401 errors

答案 5 :(得分:76)

假设你有

double d = 9232.129394d;

您可以使用BigDecimal

BigDecimal bd = new BigDecimal(d).setScale(2, RoundingMode.HALF_EVEN);
d = bd.doubleValue();

或没有BigDecimal

d = Math.round(d*100)/100.0d;

同时使用两个解决方案d == 9232.13

答案 6 :(得分:55)

您可以使用DecimalFormat类。

double d = 3.76628729;

DecimalFormat newFormat = new DecimalFormat("#.##");
double twoDecimal =  Double.valueOf(newFormat.format(d));

答案 7 :(得分:34)

Real的Java How-to posts此解决方案,它也兼容Java 1.6之前的版本。

BigDecimal bd = new BigDecimal(Double.toString(d));
bd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP);
return bd.doubleValue();

答案 8 :(得分:31)

double myNum = .912385;
int precision = 10000; //keep 4 digits
myNum= Math.floor(myNum * precision +.5)/precision;

答案 9 :(得分:29)

@Milhous:舍入的十进制格式非常好:

  

您也可以使用

DecimalFormat df = new DecimalFormat("#.00000");
df.format(0.912385);
     

确保你有0的结尾。

我想补充一点,这种方法非常擅长提供实际的 数字,舍入机制 - 不仅在视觉上,而且在处理时。

假设:您必须在GUI中实现舍入机制 程序。简单地改变结果输出的准确度/精度 更改插入符号格式(即在括号内)。那样:

DecimalFormat df = new DecimalFormat("#0.######");
df.format(0.912385);

将作为输出返回:0.912385

DecimalFormat df = new DecimalFormat("#0.#####");
df.format(0.912385);

将作为输出返回:0.91239

DecimalFormat df = new DecimalFormat("#0.####");
df.format(0.912385);

将作为输出返回:0.9124

[编辑:如果插入符号格式如此(“#0。############”)并且你 输入小数,例如3.1415926,为了论证,DecimalFormat 不产生任何垃圾(例如尾随零)并将返回: 3.1415926 ..如果你这样倾向。当然,它有点冗长 对于一些开发人员的喜好 - 但是嘿,它的内存占用很少 在处理过程中非常容易实现。]

基本上,DecimalFormat的优点在于它同时处理字符串 外观 - 以及舍入精度设置的级别。 Ergo:你 以一个代码实现的价格获得两个好处。 ;)

答案 10 :(得分:18)

您可以使用以下实用程序方法 -

public static double round(double valueToRound, int numberOfDecimalPlaces)
{
    double multipicationFactor = Math.pow(10, numberOfDecimalPlaces);
    double interestedInZeroDPs = valueToRound * multipicationFactor;
    return Math.round(interestedInZeroDPs) / multipicationFactor;
}

答案 11 :(得分:10)

简洁的解决方案:

   public static double round(double value, int precision) {
      int scale = (int) Math.pow(10, precision);
      return (double) Math.round(value * scale) / scale;
  }

另请参阅https://stackoverflow.com/a/22186845/212950 感谢jpdymond提供此功能。

答案 12 :(得分:8)

您可以使用BigDecimal

BigDecimal value = new BigDecimal("2.3");
value = value.setScale(0, RoundingMode.UP);
BigDecimal value1 = new BigDecimal("-2.3");
value1 = value1.setScale(0, RoundingMode.UP);
System.out.println(value + "n" + value1);

参考:http://www.javabeat.net/precise-rounding-of-decimals-using-rounding-mode-enumeration/

答案 13 :(得分:7)

如果你真的想要十进制数来计算(而不仅仅是输出),不要使用像double这样的基于二进制的浮点格式。

Use BigDecimal or any other decimal-based format.

我确实使用BigDecimal进行计算,但要记住它取决于大小 你正在处理的数字。在我的大多数实现中,我发现从double或者解析 整数到Long足以进行大量计算。

事实上,我已经 最近使用parsed-to-Long来获得准确的表示(与hex结果相反) 在GUI中,数字与#################################字符一样大(作为 例子)。

答案 14 :(得分:7)

试试这个:org.apache.commons.math3.util.Precision.round(double x,int scale)

请参阅:http://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math3/util/Precision.html

Apache Commons数学图书馆主页是:http://commons.apache.org/proper/commons-math/index.html

此方法的内部实现是:

public static double round(double x, int scale) {
    return round(x, scale, BigDecimal.ROUND_HALF_UP);
}

public static double round(double x, int scale, int roundingMethod) {
    try {
        return (new BigDecimal
               (Double.toString(x))
               .setScale(scale, roundingMethod))
               .doubleValue();
    } catch (NumberFormatException ex) {
        if (Double.isInfinite(x)) {
            return x;
        } else {
            return Double.NaN;
        }
    }
}

答案 15 :(得分:6)

由于我没有找到关于这个主题的完整答案,我已经整理了一个应该正确处理这个问题的课程,并支持:

  • 格式化:轻松将双精度格式化为具有一定位数的字符串
  • 解析:将格式化的值解析为双重
  • 区域设置:使用默认区域设置格式化和解析
  • 指数表示法:在某个阈值后开始使用指数表示法

用法非常简单

(为了这个例子,我使用的是自定义语言环境)

public static final int DECIMAL_PLACES = 2;

NumberFormatter formatter = new NumberFormatter(DECIMAL_PLACES);

String value = formatter.format(9.319); // "9,32"
String value2 = formatter.format(0.0000005); // "5,00E-7"
String value3 = formatter.format(1324134123); // "1,32E9"

double parsedValue1 = formatter.parse("0,4E-2", 0); // 0.004
double parsedValue2 = formatter.parse("0,002", 0); // 0.002
double parsedValue3 = formatter.parse("3423,12345", 0); // 3423.12345

这是班级

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.ParseException;
import java.util.Locale;

public class NumberFormatter {

    private static final String SYMBOL_INFINITE           = "\u221e";
    private static final char   SYMBOL_MINUS              = '-';
    private static final char   SYMBOL_ZERO               = '0';
    private static final int    DECIMAL_LEADING_GROUPS    = 10;
    private static final int    EXPONENTIAL_INT_THRESHOLD = 1000000000; // After this value switch to exponential notation
    private static final double EXPONENTIAL_DEC_THRESHOLD = 0.0001; // Below this value switch to exponential notation

    private DecimalFormat decimalFormat;
    private DecimalFormat decimalFormatLong;
    private DecimalFormat exponentialFormat;

    private char groupSeparator;

    public NumberFormatter(int decimalPlaces) {
        configureDecimalPlaces(decimalPlaces);
    }

    public void configureDecimalPlaces(int decimalPlaces) {
        if (decimalPlaces <= 0) {
            throw new IllegalArgumentException("Invalid decimal places");
        }

        DecimalFormatSymbols separators = new DecimalFormatSymbols(Locale.getDefault());
        separators.setMinusSign(SYMBOL_MINUS);
        separators.setZeroDigit(SYMBOL_ZERO);

        groupSeparator = separators.getGroupingSeparator();

        StringBuilder decimal = new StringBuilder();
        StringBuilder exponential = new StringBuilder("0.");

        for (int i = 0; i < DECIMAL_LEADING_GROUPS; i++) {
            decimal.append("###").append(i == DECIMAL_LEADING_GROUPS - 1 ? "." : ",");
        }

        for (int i = 0; i < decimalPlaces; i++) {
            decimal.append("#");
            exponential.append("0");
        }

        exponential.append("E0");

        decimalFormat = new DecimalFormat(decimal.toString(), separators);
        decimalFormatLong = new DecimalFormat(decimal.append("####").toString(), separators);
        exponentialFormat = new DecimalFormat(exponential.toString(), separators);

        decimalFormat.setRoundingMode(RoundingMode.HALF_UP);
        decimalFormatLong.setRoundingMode(RoundingMode.HALF_UP);
        exponentialFormat.setRoundingMode(RoundingMode.HALF_UP);
    }

    public String format(double value) {
        String result;
        if (Double.isNaN(value)) {
            result = "";
        } else if (Double.isInfinite(value)) {
            result = String.valueOf(SYMBOL_INFINITE);
        } else {
            double absValue = Math.abs(value);
            if (absValue >= 1) {
                if (absValue >= EXPONENTIAL_INT_THRESHOLD) {
                    value = Math.floor(value);
                    result = exponentialFormat.format(value);
                } else {
                    result = decimalFormat.format(value);
                }
            } else if (absValue < 1 && absValue > 0) {
                if (absValue >= EXPONENTIAL_DEC_THRESHOLD) {
                    result = decimalFormat.format(value);
                    if (result.equalsIgnoreCase("0")) {
                        result = decimalFormatLong.format(value);
                    }
                } else {
                    result = exponentialFormat.format(value);
                }
            } else {
                result = "0";
            }
        }
        return result;
    }

    public String formatWithoutGroupSeparators(double value) {
        return removeGroupSeparators(format(value));
    }

    public double parse(String value, double defValue) {
        try {
            return decimalFormat.parse(value).doubleValue();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return defValue;
    }

    private String removeGroupSeparators(String number) {
        return number.replace(String.valueOf(groupSeparator), "");
    }

}

答案 16 :(得分:5)

以防有人仍然需要帮助。这个解决方案非常适合我。

private String withNoTrailingZeros(final double value, final int nrOfDecimals) {
return new BigDecimal(String.valueOf(value)).setScale(nrOfDecimals,  BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString();

}

返回带有所需输出的 String

答案 17 :(得分:4)

下面的代码段显示了如何显示n位数。诀窍是将变量pp设置为1,然后设置n个零。在下面的示例中,变量pp值有5个零,因此将显示5个数字。

double pp = 10000;

double myVal = 22.268699999999967;
String needVal = "22.2687";

double i = (5.0/pp);

String format = "%10.4f";
String getVal = String.format(format,(Math.round((myVal +i)*pp)/pp)-i).trim();

答案 18 :(得分:4)

为实现这一目标,我们可以使用此格式化程序:

 DecimalFormat df = new DecimalFormat("#.00");
 String resultado = df.format(valor)

或:

DecimalFormat df = new DecimalFormat("0.00"); :

使用此方法始终获得两位小数:

   private static String getTwoDecimals(double value){
      DecimalFormat df = new DecimalFormat("0.00"); 
      return df.format(value);
    }

定义此值:

91.32
5.22
11.5
1.2
2.6

使用该方法我们可以得到这样的结果:

91.32
5.22
11.50
1.20
2.60

demo online.

答案 19 :(得分:4)

如果您使用DecimalFormatdouble转换为String,则非常简单:

DecimalFormat formatter = new DecimalFormat("0.0##");
formatter.setRoundingMode(RoundingMode.HALF_UP);

double num = 1.234567;
return formatter.format(num);

有几个RoundingMode枚举值可供选择,具体取决于您需要的行为。

答案 20 :(得分:4)

我来到这里只是想要一个关于如何围绕数字的简单答案。这是提供这一点的补充答案。

如何在Java中对数字进行舍入

最常见的情况是使用Math.round()

Math.round(3.7) // 4

数字四舍五入到最接近的整数。向上舍入.5值。如果您需要不同的舍入行为,则可以使用其他Math函数之一。请参阅下面的比较。

round

如上所述,这轮到最接近的整数。舍入.5小数。此方法返回int

Math.round(3.0); // 3
Math.round(3.1); // 3
Math.round(3.5); // 4
Math.round(3.9); // 4

Math.round(-3.0); // -3
Math.round(-3.1); // -3
Math.round(-3.5); // -3 *** careful here ***
Math.round(-3.9); // -4

ceil

任何十进制值都会向上舍入到下一个整数。它进入了 ceil 。此方法返回double

Math.ceil(3.0); // 3.0
Math.ceil(3.1); // 4.0
Math.ceil(3.5); // 4.0
Math.ceil(3.9); // 4.0

Math.ceil(-3.0); // -3.0
Math.ceil(-3.1); // -3.0
Math.ceil(-3.5); // -3.0
Math.ceil(-3.9); // -3.0

floor

任何十进制值都向下舍入到下一个整数。此方法返回double

Math.floor(3.0); // 3.0
Math.floor(3.1); // 3.0
Math.floor(3.5); // 3.0
Math.floor(3.9); // 3.0

Math.floor(-3.0); // -3.0
Math.floor(-3.1); // -4.0
Math.floor(-3.5); // -4.0
Math.floor(-3.9); // -4.0

rint

这类似于round,十进制值四舍五入到最接近的整数。但是,与round不同,.5值舍入为偶数。此方法返回double

Math.rint(3.0); // 3.0
Math.rint(3.1); // 3.0
Math.rint(3.5); // 4.0 ***
Math.rint(3.9); // 4.0
Math.rint(4.5); // 4.0 ***
Math.rint(5.5); // 6.0 ***

Math.rint(-3.0); // -3.0
Math.rint(-3.1); // -3.0
Math.rint(-3.5); // -4.0 ***
Math.rint(-3.9); // -4.0
Math.rint(-4.5); // -4.0 ***
Math.rint(-5.5); // -6.0 ***

答案 21 :(得分:3)

我同意所选择的答案,使用DecimalFormat ---或BigDecimal

请先阅读下面的更新

但是,如果你想要对double值进行舍入并获得double值结果,则可以使用上面提到的org.apache.commons.math3.util.Precision.round(..)。实现使用BigDecimal,速度很慢并且会产生垃圾。

decimal4j库中的DoubleRounder实用程序提供了类似但快速且无垃圾的方法:

 double a = DoubleRounder.round(2.0/3.0, 3);
 double b = DoubleRounder.round(2.0/3.0, 3, RoundingMode.DOWN);
 double c = DoubleRounder.round(1000.0d, 17);
 double d = DoubleRounder.round(90080070060.1d, 9);
 System.out.println(a);
 System.out.println(b);
 System.out.println(c);
 System.out.println(d);

将输出

 0.667
 0.666
 1000.0
 9.00800700601E10

请参阅 https://github.com/tools4j/decimal4j/wiki/DoubleRounder-Utility

免责声明:我参与了decimal4j项目。

<强>更新 正如@iaforek所指出的,DoubleRounder有时会返回违反直觉的结果。原因是它在数学上执行正确的舍入。例如,DoubleRounder.round(256.025d, 2)将向下舍入为256.02,因为表示为256.025d的double值稍微小于有理值256.025,因此将向下舍入。

备注:

  • 此行为与BigDecimal(double)构造函数的行为非常相似(但不是valueOf(double)使用字符串构造函数的行为)。
  • 首先可以通过双舍入步骤避免问题达到更高的精度,但这很复杂,我不会详细介绍

由于这些原因以及本文中上面提到的所有内容,我不建议使用DoubleRounder

答案 22 :(得分:3)

如果您使用的是具有最小JDK的技术。这是一种没有任何Java库的方法:

double scale = 100000;    
double myVal = 0.912385;
double rounded = (int)((myVal * scale) + 0.5d) / scale;

答案 23 :(得分:2)

DecimalFormat是输出的最佳方式,但我不喜欢它。我总是这样做,因为它返回double值。所以我可以使用它而不仅仅是输出。

Math.round(selfEvaluate*100000d.0)/100000d.0;

OR

Math.round(selfEvaluate*100000d.0)*0.00000d1;

如果需要大小数位值,则可以使用BigDecimal。无论如何.0很重要。没有它,0.33333d5的舍入返回0.33333,只允许9位数。没有.0的第二个函数存在0.30000返回0.30000000000000004的问题。

答案 24 :(得分:2)

这是我的答案:

double num = 4.898979485566356;
DecimalFormat df = new DecimalFormat("#.##");      
time = Double.valueOf(df.format(num));

System.out.println(num); // 4.89

答案 25 :(得分:1)

请记住,String.format()和DecimalFormat使用默认的Locale生成字符串。因此,他们可以使用点或逗号作为整数和小数部分之间的分隔符来编写带格式的数字。要确保舍入的String符合您想要的格式,请使用java.text.NumberFormat:

  Locale locale = Locale.ENGLISH;
  NumberFormat nf = NumberFormat.getNumberInstance(locale);
  // for trailing zeros:
  nf.setMinimumFractionDigits(2);
  // round to 2 digits:
  nf.setMaximumFractionDigits(2);

  System.out.println(nf.format(.99));
  System.out.println(nf.format(123.567));
  System.out.println(nf.format(123.0));

将以英语区域设置打印(无论您的语言环境是什么):   0.99   123.57   123.00

该例子来自Farenda - how to convert double to String correctly

答案 26 :(得分:1)

dp =您想要的小数位数, 和是双倍的。

    double p = Math.pow(10d, dp);

    double result = Math.round(value * p)/p;

答案 27 :(得分:1)

因此,在阅读了大多数答案之后,我意识到其中大多数都不是精确的,实际上使用BigDecimal似乎是最佳选择,但是如果您不了解RoundingMode工程,您将不可避免地失去精度。当在项目中处理大量数字时,我想到了这一点,并认为它可以帮助其他难以四舍五入的数字。例如。

BigDecimal bd = new BigDecimal("1363.2749");
bd = bd.setScale(2, RoundingMode.HALF_UP);
System.out.println(bd.doubleValue());

您期望获得1363.28作为输出,但是如果您不知道1363.27在做什么,则最终会得到RoundingMode,这是不期望的。因此,深入研究Oracle Docs,您将发现以下有关RoundingMode.HALF_UP的描述。

  

除非双方都采用,否则舍入模式将舍入为“最近的邻居”   邻居是等距的,在这种情况下会四舍五入。

因此知道这一点,我们意识到除非获得四舍五入的结果,否则我们将不会获得精确的舍入。因此,为了完成足够的回合,我们需要从n-1十进制到所需的十进制数字循环。例如。

private double round(double value, int places) throws IllegalArgumentException {

    if (places < 0) throw new IllegalArgumentException();

    // Cast the number to a String and then separate the decimals.
    String stringValue = Double.toString(value);
    String decimals = stringValue.split("\\.")[1];

    // Round all the way to the desired number.
    BigDecimal bd = new BigDecimal(stringValue);
    for (int i = decimals.length()-1; i >= places; i--) {
        bd = bd.setScale(i, RoundingMode.HALF_UP);
    }

    return bd.doubleValue();
}

这最终将为我们提供预期的输出,即1363.28

答案 28 :(得分:1)

我在Java 8中使用过波纹管,它对我有用

    double amount = 1000.431;        
    NumberFormat formatter = new DecimalFormat("##.00");
    String output = formatter.format(amount);
    System.out.println("output = " + output);

输出:

output = 1000.43

答案 29 :(得分:1)

public static double formatDecimal(double amount) {
    BigDecimal amt = new BigDecimal(amount);
    amt = amt.divide(new BigDecimal(1), 2, BigDecimal.ROUND_HALF_EVEN);
    return amt.doubleValue();
}

使用 Junit 进行测试

@RunWith(Parameterized.class)
public class DecimalValueParameterizedTest {

  @Parameterized.Parameter
  public double amount;

  @Parameterized.Parameter(1)
  public double expectedValue;

@Parameterized.Parameters
public static List<Object[]> dataSets() {
    return Arrays.asList(new Object[][]{
            {1000.0, 1000.0},
            {1000, 1000.0},
            {1000.00000, 1000.0},
            {1000.01, 1000.01},
            {1000.1, 1000.10},
            {1000.001, 1000.0},
            {1000.005, 1000.0},
            {1000.007, 1000.01},
            {1000.999, 1001.0},
            {1000.111, 1000.11}
    });
}

@Test
public void testDecimalFormat() {
    Assert.assertEquals(expectedValue, formatDecimal(amount), 0.00);
}

答案 30 :(得分:0)

如果考虑5或n个小数。 可能是这个答案可以解决你的问题。

    double a = 123.00449;
    double roundOff1 = Math.round(a*10000)/10000.00;
    double roundOff2 = Math.round(roundOff1*1000)/1000.00;
    double roundOff = Math.round(roundOff2*100)/100.00;

    System.out.println("result:"+roundOff);

输出将是: 123.0 1 这可以通过循环和递归函数来解决。

答案 31 :(得分:0)

通常,通过缩放来完成舍入:round(num / p) * p

/**
 * MidpointRounding away from zero ('arithmetic' rounding)
 * Uses a half-epsilon for correction. (This offsets IEEE-754
 * half-to-even rounding that was applied at the edge cases).
 */
double RoundCorrect(double num, int precision) {
    double c = 0.5 * EPSILON * num;
//  double p = Math.pow(10, precision); //slow
    double p = 1; while (precision--> 0) p *= 10;
    if (num < 0)
        p *= -1;
    return Math.round((num + c) * p) / p;
}

// testing edge cases
RoundCorrect(1.005, 2);   // 1.01 correct
RoundCorrect(2.175, 2);   // 2.18 correct
RoundCorrect(5.015, 2);   // 5.02 correct

RoundCorrect(-1.005, 2);  // -1.01 correct
RoundCorrect(-2.175, 2);  // -2.18 correct
RoundCorrect(-5.015, 2);  // -5.02 correct

答案 32 :(得分:0)

如果需要(map (fn [[obj-name obj-properties]] (conj (flatten (seq obj-properties)) obj-name)) obj-lookup) 可以使用以下方法

double

例如double getRandom(int decimalPoints) { double a = Math.random(); int multiplier = (int) Math.pow(10, decimalPoints); int b = (int) (a * multiplier); return b / (double) multiplier; }

答案 33 :(得分:0)

  1. 为了使尾随0上升到第5位
DecimalFormat decimalFormatter = new DecimalFormat("#.00000");
decimalFormatter.format(0.350500); // result 0.350500
  1. 为避免0位尾随第5位
DecimalFormat decimalFormatter= new DecimalFormat("#.#####");
decimalFormatter.format(0.350500); // result o.3505

答案 34 :(得分:0)

比较小数位数是否受限的简单方法。 可以使用Casting代替DecimalFormat,Math或BigDecimal!

这是样本

public static boolean threeDecimalPlaces(double value1, double value2){
    boolean isEqual = false;
    // value1 = 3.1756 
    // value2 = 3.17
    //(int) (value1 * 1000) = 3175
    //(int) (value2 * 1000) = 3170

    if ((int) (value1 * 1000) == (int) (value2 * 1000)){
        areEqual = true;
    }

    return isEqual;
}