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

发布于 2024-12-10 03:55:49 字数 40 浏览 6 评论 0 原文

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

For example I have the variable 3.545555555, which I would want to truncate to just 3.54.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(19

信仰 2024-12-17 03:55:50

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

感谢@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
(当我使用随机数生成时,每次执行都会发生变化)

I was looking for a two decimal random number generator whether it is a float or double, i really don't mind. I started with floating number and ended returning double. With the help of the code above from @Rainbow979 with minor changes it worked perfectly. Instead of Math.round, I used Math.floor.

thanks to @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));
}

Output: 1088.48
(changes for every execution as I used randon number generation)

我一向站在原地 2024-12-17 03:55:50

这对我有用:

double input = 104.8695412  //For example

long roundedInt = Math.round(input * 100);
double result = (double) roundedInt/100;

//result == 104.87

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

This worked for me:

double input = 104.8695412  //For example

long roundedInt = Math.round(input * 100);
double result = (double) roundedInt/100;

//result == 104.87

I personally like this version because it actually performs the rounding numerically, rather than by converting it to a String (or similar) and then formatting it.

溺ぐ爱和你が 2024-12-17 03:55:49

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

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

如果需要它进行计算,请使用java.lang.Math

 Math.floor(value * 100) / 100;

If you want that for display purposes, use java.text.DecimalFormat:

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

If you need it for calculations, use java.lang.Math:

 Math.floor(value * 100) / 100;
波浪屿的海角声 2024-12-17 03:55:49
DecimalFormat df = new DecimalFormat(fmt);
df.setRoundingMode(RoundingMode.DOWN);
s = df.format(d);

检查可用的 RoundingModeDecimalFormat

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

Check available RoundingMode and DecimalFormat.

当梦初醒 2024-12-17 03:55:49

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

如何将数字四舍五入到小数点n Java 中的地方 link

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

None of the other answers worked for both positive and negative values ( I mean for the calculation and just to do "truncate" without Rounding). and without converting to string.

From the How to round a number to n decimal places in Java link

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);
    }
}

This method worked fine for me .

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));

Results :

0.00
9.62
9.62
9.62
9.62
9.99
-9.99
-9.00
绝情姑娘 2024-12-17 03:55:49

首先请注意,double 是一个二进制分数,并且实际上没有 小数位。

如果需要小数位,请使用 BigDecimal,它具有用于截断的 setScale() 方法,或使用 DecimalFormat 获取 字符串

Note first that a double is a binary fraction and does not really have decimal places.

If you need decimal places, use a BigDecimal, which has a setScale() method for truncation, or use DecimalFormat to get a String.

小瓶盖 2024-12-17 03:55:49

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

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

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

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

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

Formating as a string and converting back to double i think will give you the result you want.

The double value will not be round(), floor() or ceil().

A quick fix for it could be:

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

You can use the sValue for display purposes or the newValue for calculation.

入怼 2024-12-17 03:55:49

如果出于某种原因,您不想使用 BigDecimal,您可以将 double 转换为 int 来截断它。

如果要截断到 个位 位置:

  • 只需转换为 int

十位 位置:

  • 乘以 10 转换
  • int< /code>
  • 转换回 double
  • 并除以 10。

Hundreths 个位置

  • 乘以 100 并除以 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舍入到个位,负一到十位, ETC。)

If, for whatever reason, you don't want to use a BigDecimal you can cast your double to an int to truncate it.

If you want to truncate to the Ones place:

  • simply cast to int

To the Tenths place:

  • multiply by ten
  • cast to int
  • cast back to double
  • and divide by ten.

Hundreths place

  • multiply and divide by 100 etc.

Example:

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;
}

In this example, decimalPlaces would be the number of places PAST the ones place you wish to go, so 1 would round to the tenths place, 2 to the hundredths, and so on (0 rounds to the ones place, and negative one to the tens, etc.)

仅一夜美梦 2024-12-17 03:55:49

您可以使用 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

You can use NumberFormat Class object to accomplish the task.

// 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
朮生 2024-12-17 03:55:49

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

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

    df.setRoundingMode(RoundingMode.FLOOR);

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

这将给出 = 3.54!

3.545555555 to get 3.54.
Try Following for this:

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

    df.setRoundingMode(RoundingMode.FLOOR);

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

This will give= 3.54!

心房的律动 2024-12-17 03:55:49

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

Maybe Math.floor(value * 100) / 100? Beware that the values like 3.54 may be not exactly represented with a double.

温折酒 2024-12-17 03:55:49

这是我使用的方法:

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;

Here is the method I use:

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

This can also be done:

a=Math.floor(a*100) / 100;
虚拟世界 2024-12-17 03:55:49

我使用 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

I used Math.floor() method and basic moving of decimal places by (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
牵你手 2024-12-17 03:55:49

快速检查是使用 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;
}

A quick check is to use the Math.floor method. I created a method to check a double for two or less decimal places below:

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;
}
剩一世无双 2024-12-17 03:55:49

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

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

这对积极和消极的人都有效。负值。

In this solution, this will TRUNCATE a double to only two decimal places. This solution will not ROUND OFF the double value.

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

This will output 3.54

DecimalFormat("#.##") - Here, I entered two hash symbols(##) after the decimal point. Hence, this will truncate the number up to two decimal places.

This will work for both Positive & Negative values.

别再吹冷风 2024-12-17 03:55:49

也许如下:

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

Maybe following :

double roundTwoDecimals(double d) { 
      DecimalFormat twoDForm = new DecimalFormat("#.##"); 
      return Double.valueOf(twoDForm.format(d));
}  
你爱我像她 2024-12-17 03:55:49

我有一个稍微修改过的 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

I have a slightly modified version of Mani's.

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));

}

Output:

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
假扮的天使 2024-12-17 03:55:49
      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);
      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);
野侃 2024-12-17 03:55:49

双第一值=-3.1756d;

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

double firstValue = -3.1756d;

double value1 = (((int)(Math.pow(10,3)*firstValue))/Math.pow(10,3));

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文