java中是否有截断双精度的函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1976809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 02:00:37  来源:igfitidea点击:

Are there any functions for truncating a double in java?

java

提问by

Is there a Java Library function which can be used to truncate a number to an arbitrary number of decimal places? For Example.

是否有可用于将数字截断为任意小数位数的 Java 库函数?例如。

SomeLibrary.truncate(1.575, 2) = 1.57

Thanks

谢谢

采纳答案by raoulsson

Try setScale of BigDecimallike so:

像这样尝试BigDecimal 的setScale :

public static double round(double d, int decimalPlace) {
    BigDecimal bd = new BigDecimal(d);
    bd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP);
    return bd.doubleValue();
}

回答by Stefan Kendall

For most numbers, you won't be able to get an exact representation of xxx.yyyyunless you use a decimal class with guaranteed accuracy, such as BigDecimal.

对于大多数数字,xxx.yyyy除非您使用具有保证精度的十进制类(例如BigDecimal ),否则您将无法获得 的精确表示。

回答by quant_dev

To do it 100% reliably, you'd have to pass the argument as string, not as floating-point number. When given as string, the code is easy to write. The reason for this is that

要做到 100% 可靠,您必须将参数作为字符串传递,而不是作为浮点数传递。当以字符串形式给出时,代码很容易编写。这样做的原因是

double x = 1.1;

does not mean that x will actually evaluate to 1.1, only to the closest exactly representable number.

并不意味着 x 实际上会计算为 1.1,只会计算为最接近的完全可表示的数字。

回答by Berek Bryan

created a method to do it.

创建了一个方法来做到这一点。

public double roundDouble(double d, int places) {
    return Math.round(d * Math.pow(10, (double) places)) / Math.pow(10, (double)places);
}

回答by Nathan Hughes

There's one in commons-math. Check out http://commons.apache.org/math/apidocs/org/apache/commons/math/util/MathUtils.html:

公共数学中有一个。查看http://commons.apache.org/math/apidocs/org/apache/commons/math/util/MathUtils.html

public static double round(double x,
                           int scale)

It's implemented using BigDecimal, and is overloaded to allow specifying a rounding method, so you can use it to truncate, like this:

它使用 BigDecimal 实现,并被重载以允许指定舍入方法,因此您可以使用它来截断,如下所示:

org.apache.commons.math.util.MathUtils.round(1.575, 2, 
    java.math.BigDecimal.ROUND_DOWN);

Update:

更新:

In the last version (Math3), this method is in the class Precision. org.apache.commons.math3.util.Precision.round(double x, int scale, int roundingMethod)

在最新版本 (Math3) 中,此方法位于类中Precisionorg.apache.commons.math3.util.Precision.round(double x, int scale, int roundingMethod)

回答by Powerlord

Actually, this sort of thing is easy to write:

实际上,这种事情很容易写:

public static double truncate(double value, int places) {
    double multiplier = Math.pow(10, places);
    return Math.floor(multiplier * value) / multiplier;
}

Note that it's Math.floor, because Math.round wouldn't be truncating.

请注意,它是 Math.floor,因为 Math.round 不会被截断。

Oh, and this returns a double, because that's what most functions in the Math class return (like Math.pow and Math.floor).

哦,这会返回一个双精度值,因为这是 Math 类中的大多数函数返回的值(如 Math.pow 和 Math.floor)。

Caveat: Doubles suck for accuracy. One of the BigDecimal solutions should be considered first.

警告:双打的准确性很差。应首先考虑 BigDecimal 解决方案之一。

回答by Esko

Incredible no one brought this up yet, Java API has had DecimalFormatfor ages now for this exact purpose.

令人难以置信的是,现在还没有人提出这个问题,Java API 已经为此目的而使用DecimalFormat已有很长时间了。

回答by Peter Lawrey

here is a short implementation which is many times faster than using BigDecimal or Math.pow

这是一个简短的实现,比使用 BigDecimal 或 Math.pow 快很多倍

private static long TENS[] = new long[19];
static {
    TENS[0] = 1;
    for (int i = 1; i < TENS.length; i++) TENS[i] = 10 * TENS[i - 1];
}

public static double round(double v, int precision) {
    assert precision >= 0 && precision < TENS.length;
    double unscaled = v * TENS[precision];
    if(unscaled < Long.MIN_VALUE || unscaled > Long.MAX_VALUE) 
       return v;
    long unscaledLong = (long) (unscaled + (v < 0 ? -0.5 : 0.5));
    return (double) unscaledLong / TENS[precision];
}

Delete the assert'ions to taste. ;)

删除断言以品尝。;)

回答by Syed Mustaffa

Use this simple function

使用这个简单的功能

double truncateDouble(double number, int numDigits) {
    double result = number;
    String arg = "" + number;
    int idx = arg.indexOf('.');
    if (idx!=-1) {
        if (arg.length() > idx+numDigits) {
            arg = arg.substring(0,idx+numDigits+1);
            result  = Double.parseDouble(arg);
        }
    }
    return result ;
}

回答by dvsaura

I just want to add to ubuntudroid's solution. I tried it and it wouldn't round down, so I had to add

我只想添加到 ubuntudroid 的解决方案中。我试过了,它不会四舍五入,所以我不得不补充

df.setRoundingMode(RoundingMode.FLOOR);

for it to work.

让它工作。