@ solusion rekurencyjnych'S (Przyjęty odpowiedź) jest w 100% rację. Właśnie dodaję przykładowy kod do twojego odniesienia.
Moja sprawa to wyświetlenie ceny z dwoma cyframi dziesiętnymi.Jest to część odpowiedzi zaplecza: "price": 2300, "currencySymbol": "CD", ...
.
To moja klasa pomocnika:
public class CurrencyUtils
{
private static final String[] suffix = { "", "K", "M" };
public static String getCompactStringForDisplay(final int amount)
{
int suffixIndex;
if (amount >= 1_000_000) {
suffixIndex = 2;
} else if (amount >= 1_000) {
suffixIndex = 1;
} else {
suffixIndex = 0;
}
int quotient;
int remainder;
if (amount >= 1_000_000) {
quotient = amount/1_000_000;
remainder = amount % 1_000_000;
} else if (amount >= 1_000) {
quotient = amount/1_000;
remainder = amount % 1_000;
} else {
return String.valueOf(amount);
}
if (remainder == 0) {
return String.valueOf(quotient) + suffix[suffixIndex];
}
// Keep two most significant digits
if (remainder >= 10_000) {
remainder /= 10_000;
} else if (remainder >= 1_000) {
remainder /= 1_000;
} else if (remainder >= 100) {
remainder /= 10;
}
return String.valueOf(quotient) + '.' + String.valueOf(remainder) + suffix[suffixIndex];
}
}
To moja klasa testu (na podstawie JUnit 4):
public class CurrencyUtilsTest {
@Test
public void getCompactStringForDisplay() throws Exception {
int[] numbers = {0, 5, 999, 1_000, 5_821, 10_500, 101_800, 2_000_000, 7_800_000, 92_150_000, 123_200_000, 9_999_999};
String[] expected = {"0", "5", "999", "1K", "5.82K", "10.50K", "101.80K", "2M", "7.80M", "92.15M", "123.20M", "9.99M"};
for (int i = 0; i < numbers.length; i++) {
int n = numbers[i];
String formatted = CurrencyUtils.getCompactStringForDisplay(n);
System.out.println(n + " => " + formatted);
assertEquals(expected[i], formatted);
}
}
}
w Javie to nie będzie działać, jeśli nie 1,0% 0,1 – endless
@ Bezczasowy: Prawda, najpierw musisz przekonwertować na liczbę całkowitą. Musisz również określić, co masz na myśli przez pozostałą część dwóch zmiennych, ponieważ jest to zwykle określane w kategoriach arytmetyki całkowitej. – recursive
Po prostu, jeśli ktoś przejdzie to pytanie i zastanawia się, w jaki sposób uzyskałbyś nie iloraz, ale największą naturalną liczbę <= iloraz lub mod możesz użyć funkcji w pakiecie matematycznym: 'Math.floorDiv (x, y)' oraz 'Math.floorMod (x, y)' –