Ich habe folgende Funktion, die bei einem Double-Wert die Nachkommastellen so entfernt, dass es nur noch zwei gibt.
Ich möchte aber, dass nicht einfach abgeschnitten wird, sondern gerundet wird.
Für drei Nachkommastellen habe ich bereits folgende Funktion implementiert.
Java:
public static double getDoubleValueWithMaxTwoDigitsAfterTheComma(double d) {
String s = "" + d;
if (s.length() > 4) {
s = s.substring(0, 4);
}
if (s.contains("E")) {
s = "0d";
}
d = Double.parseDouble(s);
return d;
}
Ich möchte aber, dass nicht einfach abgeschnitten wird, sondern gerundet wird.
Für drei Nachkommastellen habe ich bereits folgende Funktion implementiert.
Java:
public static double getDoubleValueWithMaxThreeDigitsAfterTheCommaWithRounding(double d) {
String s = "" + d;
if (s.contains("E")) {
s = "0d";
}
if (s.length() > 5) {
int firstDigitAfterComma = Integer.parseInt(s.substring(2, 3));
int secondDigitAfterComma = Integer.parseInt(s.substring(3, 4));
int thirdDigitAfterComma = Integer.parseInt(s.substring(4, 5));
int fourthDigitAfterComma = Integer.parseInt(s.substring(5, 6));
boolean increaseThirdDigitByOne = false;
boolean increaseSecondDigitByOne = false;
boolean increaseFirstDigitByOne = false;
boolean increaseNumberBeforeCommaByOne = false;
if (fourthDigitAfterComma == 5 || fourthDigitAfterComma == 6 || fourthDigitAfterComma == 7 || fourthDigitAfterComma == 8 || fourthDigitAfterComma == 9) {
increaseThirdDigitByOne = true;
if (thirdDigitAfterComma <= 8) {
thirdDigitAfterComma = thirdDigitAfterComma + 1;
} else {
thirdDigitAfterComma = 0;
increaseSecondDigitByOne = true;
}
if (increaseSecondDigitByOne) {
if (secondDigitAfterComma <= 8) {
secondDigitAfterComma = secondDigitAfterComma + 1;
} else {
secondDigitAfterComma = 0;
increaseFirstDigitByOne = true;
}
}
if (increaseFirstDigitByOne) {
if (firstDigitAfterComma <= 8) {
firstDigitAfterComma = firstDigitAfterComma + 1;
} else {
increaseNumberBeforeCommaByOne = true;
}
}
}
if (increaseNumberBeforeCommaByOne) {
s = "1";
} else {
s = "0." + firstDigitAfterComma + secondDigitAfterComma + thirdDigitAfterComma;
}
}
d = Double.parseDouble(s);
return d;
}