如何在 Java 中将双精度数截断为仅保留两位小数?

问题描述 投票:0回答:19

例如,我有变量 3.545555555,我想将其截断为 3.54。

java double truncate decimalformat
19个回答
175
投票

如果您希望将其用于显示目的,请使用

java.text.DecimalFormat
:

 new DecimalFormat("#.##").format(dblVar);

如果您需要它进行计算,请使用

java.lang.Math

 Math.floor(value * 100) / 100;

47
投票
DecimalFormat df = new DecimalFormat(fmt);
df.setRoundingMode(RoundingMode.DOWN);
s = df.format(d);

检查可用

RoundingMode
DecimalFormat


31
投票

其他答案都不适用于正值和负值(我的意思是用于计算并且只是在不进行舍入的情况下进行“截断”)。并且无需转换为字符串。

来自 如何在 Java 中将数字四舍五入到小数点后 n 位链接

private static BigDecimal truncateDecimal(double x,int numberofDecimals)
{
    if ( x > 0) {
        return new BigDecimal(String.valueOf(x)).setScale(numberofDecimals, BigDecimal.ROUND_FLOOR);
    } else {
        return new BigDecimal(String.valueOf(x)).setScale(numberofDecimals, BigDecimal.ROUND_CEILING);
    }
}

这个方法对我来说效果很好。

System.out.println(truncateDecimal(0, 2));
    System.out.println(truncateDecimal(9.62, 2));
    System.out.println(truncateDecimal(9.621, 2));
    System.out.println(truncateDecimal(9.629, 2));
    System.out.println(truncateDecimal(9.625, 2));
    System.out.println(truncateDecimal(9.999, 2));
    System.out.println(truncateDecimal(-9.999, 2));
    System.out.println(truncateDecimal(-9.0, 2));

结果:

0.00
9.62
9.62
9.62
9.62
9.99
-9.99
-9.00

9
投票

首先请注意,

double
是二进制分数,实际上并没有小数位。

如果需要小数位,请使用

BigDecimal
,它具有
setScale()
截断方法,或使用
DecimalFormat
获得
String


9
投票

格式化为字符串并转换回双精度我认为会给你你想要的结果。

double 值不会是 round()、floor() 或 ceil()。

一个快速解决方案可能是:

 String sValue = (String) String.format("%.2f", oldValue);
 Double newValue = Double.parseDouble(sValue);

您可以使用 sValue 进行显示或使用 newValue 进行计算。


7
投票

如果出于某种原因,您不想使用

BigDecimal
,您可以将
double
转换为
int
来截断它。

如果您想截断到 Ones 位置:

  • 只需投射到
    int

前往十分位处:

  • 乘以十
  • 投射到
    int
  • 投射回
    double
  • 然后除以十。

百位地方

  • 乘除100等

示例:

static double truncateTo( double unroundedNumber, int decimalPlaces ){
    int truncatedNumberInt = (int)( unroundedNumber * Math.pow( 10, decimalPlaces ) );
    double truncatedNumber = (double)( truncatedNumberInt / Math.pow( 10, decimalPlaces ) );
    return truncatedNumber;
}

在此示例中,

decimalPlaces
将是您想去的地方之后的位置数,因此 1 将四舍五入到十分位,2 将四舍五入到百分位,依此类推(0 四舍五入到个位,负一到十,等等)


6
投票

您可以使用 NumberFormat 类对象来完成该任务。

// Creating number format object to set 2 places after decimal point
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(2);            
nf.setGroupingUsed(false);

System.out.println(nf.format(precision));// Assuming precision is a double type variable

5
投票

3.545555555 得到 3.54。 为此尝试以下操作:

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

    df.setRoundingMode(RoundingMode.FLOOR);

    double result = new Double(df.format(3.545555555);

这将给出 = 3.54!


2
投票

也许

Math.floor(value * 100) / 100
?请注意,像
3.54
这样的值可能无法用
double
精确表示。


2
投票

这是我使用的方法:

double a=3.545555555; // just assigning your decimal to a variable
a=a*100;              // this sets a to 354.555555
a=Math.floor(a);      // this sets a to 354
a=a/100;              // this sets a to 3.54 and thus removing all your 5's

这也可以做到:

a=Math.floor(a*100) / 100;

2
投票

我使用了 Math.floor() 方法和小数点基本移动 (100 = 2)。

//3.545555555 to 3.54 by floor method
double x = 3.545555555;
double y = Math.floor(x * 100); //354
double z = y / 100; //3.54

1
投票

快速检查是使用 Math.floor 方法。我创建了一种方法来检查双精度数是否有两位或更少的小数位,如下:

public boolean checkTwoDecimalPlaces(double valueToCheck) {

    // Get two decimal value of input valueToCheck 
    double twoDecimalValue = Math.floor(valueToCheck * 100) / 100;

    // Return true if the twoDecimalValue is the same as valueToCheck else return false
    return twoDecimalValue == valueToCheck;
}

0
投票

也许以下:

double roundTwoDecimals(double d) { 
      DecimalFormat twoDForm = new DecimalFormat("#.##"); 
      return Double.valueOf(twoDForm.format(d));
}  

0
投票

我有一个稍微修改过的 Mani 版本。

private static BigDecimal truncateDecimal(final double x, final int numberofDecimals) {
    return new BigDecimal(String.valueOf(x)).setScale(numberofDecimals, BigDecimal.ROUND_DOWN);
}

public static void main(String[] args) {
    System.out.println(truncateDecimal(0, 2));
    System.out.println(truncateDecimal(9.62, 2));
    System.out.println(truncateDecimal(9.621, 2));
    System.out.println(truncateDecimal(9.629, 2));
    System.out.println(truncateDecimal(9.625, 2));
    System.out.println(truncateDecimal(9.999, 2));
    System.out.println(truncateDecimal(3.545555555, 2));

    System.out.println(truncateDecimal(9.0, 2));
    System.out.println(truncateDecimal(-9.62, 2));
    System.out.println(truncateDecimal(-9.621, 2));
    System.out.println(truncateDecimal(-9.629, 2));
    System.out.println(truncateDecimal(-9.625, 2));
    System.out.println(truncateDecimal(-9.999, 2));
    System.out.println(truncateDecimal(-9.0, 2));
    System.out.println(truncateDecimal(-3.545555555, 2));

}

输出:

0.00
9.62
9.62
9.62
9.62
9.99
9.00
3.54
-9.62
-9.62
-9.62
-9.62
-9.99
-9.00
-3.54

0
投票
      double value = 3.4555;
      String value1 =  String.format("% .3f", value) ;
      String value2 = value1.substring(0, value1.length() - 1);
      System.out.println(value2);         
      double doublevalue= Double.valueOf(value2);
      System.out.println(doublevalue);

0
投票

双精度第一值 = -3.1756d;

双值1 = (((int)(Math.pow(10,3)*firstValue))/Math.pow(10,3));


0
投票

在此解决方案中,这会将双精度数截断仅保留两位小数。此解决方案将不会对双精度值进行四舍五入。

double myDoubleNumber = 3.545555555; DecimalFormat df = new DecimalFormat("#.##"); df.setRoundingMode(RoundingMode.DOWN); double myDoubleNumberTruncated = Double.parseDouble(df.format(myDoubleNumber)); System.out.println(myDoubleNumberTruncated);

这将输出 3.54

DecimalFormat("#.##") - 在这里,我在小数点后输入了两个哈希符号(##)。因此,这会将数字截断至小数点后两位。

这适用于正值和负值。


0
投票
我正在寻找一个两位十进制随机数生成器,无论它是浮点数还是双精度数,我真的不介意。我从浮点数开始,最后返回双精度数。在 @Rainbow979 上面的代码的帮助下,稍作修改,它就完美地工作了。我没有使用 Math.round,而是使用 Math.floor。

感谢@Rainbow979

public static double getPrice() { Random r = new Random(); float min = 1000.00f; float max = 1500.00f; float price = r.nextFloat()*(max-min)+min; System.out.println(((Math.floor(price*100))/100)); return (((Math.floor(price*100))/100)); }
输出:1088.48
(当我使用随机数生成时,每次执行都会发生变化)


-2
投票
这对我有用:

double input = 104.8695412 //For example long roundedInt = Math.round(input * 100); double result = (double) roundedInt/100; //result == 104.87

我个人喜欢这个版本,因为它实际上以数字方式执行舍入,而不是通过将其转换为字符串(或类似的)然后对其进行格式化。

© www.soinside.com 2019 - 2024. All rights reserved.