English 中文(简体)
不同的工作方法似乎没有发挥作用。
原标题:Different rounding methods don t seem to work

The following code:

    DecimalFormat df = new DecimalFormat();
    df.setMinimumFractionDigits(2);

    int zahl1 = 10;
    int zahl2 = 18;

    double double1 = zahl1 / zahl2;
    System.out.println("Double1 = " + df.format(double1));

    double double2 = Math.ceil(zahl1 / zahl2);
    System.out.println("Double2 = " + df.format(double2));

    double double3 = Math.round((zahl1 / zahl2) * 100) / 100;
    System.out.println("Double3 = " + df.format(double3));

    float float1 = Math.round((zahl1 / zahl2) * 100) / 100;
    System.out.println("Float1  = " + df.format(float1));

    long long1 = zahl1 / zahl2;
    System.out.println("long1 = " + df.format(long1));

    long long3 = Math.round((zahl1 / zahl2) * 100) / 100;
    System.out.println("long3 = " + df.format(long3));

产出如下:

Double1 = 0,00
Double2 = 0,00
Double3 = 0,00
Float1  = 0,00
long1 = 0,00
long3 = 0,00

我现在对浮标和双倍以及 Java不怎么说,但我似乎并不完全理解如何达到我所期望的结果0.6。

我做了什么错误?

最佳回答

zahlzahl2

double double1 = zahl1 / zahl2;

uses integer division, the result of which is 0.

您将结果重新分配给“<条码> 杜布莱的变量并不重要:首先(合并)司发生,其结果随后扩大到“条码>杜布尔/代码”。

To fix, change that line to:

double double1 = zahl1 / (double)zahl2;
问题回答

你们在被另一户Integer分割成浮体时,必须投放愤怒:

(float)zahl1 /(float)zahl2

您应检查BigDecimal,该类功能如ROUND_HALF_DOWN等。





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签