@ solusion di ricorsiva (La risposta accettata) è al 100% a destra. Sto solo aggiungendo un codice di esempio per il tuo riferimento.
Il mio caso è di visualizzare il prezzo con due cifre decimali.Questo fa parte della risposta back-end: "price": 2300, "currencySymbol": "CD", ...
.
Questa è la mia classe di supporto:
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];
}
}
Questa è la mia classe di test (sulla base di 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);
}
}
}
in Java non funzionerà, se si fa 1,0% 0,1 – endless
@endless: vero, prima dovresti convertire in intero. E dovresti anche specificare cosa intendi per il resto di due float, poiché di solito è definito in termini di aritmetica intera. – recursive
Solo se qualcuno supera questa domanda e si chiede come otterresti il quoziente, ma il numero naturale più grande <= il quoziente o il mod puoi usare la funzione nel pacchetto matematico: 'Math.floorDiv (x, y)' e 'Math.floorMod (x, y)' –