This is the format you need:
val dec = DecimalFormat("#,###.##")
will print:
5.384,45
if you need always exactly 2 digits after the decimal point:
val dec = DecimalFormat("#,###.00")
Answer from forpas on Stack OverflowThis is the format you need:
val dec = DecimalFormat("#,###.##")
will print:
5.384,45
if you need always exactly 2 digits after the decimal point:
val dec = DecimalFormat("#,###.00")
The "most Kotlin-esque" way I found to do this sort of formatting is:
"%,.2f".format(Locale.GERMAN, 1234.5678) // => "1.234,57"
"%,.2f".format(Locale.ENGLISH, 1234.5678) // => "1,234.57"
"%,.2f".format(1234.5678) // => "1,234.57" for me, in en_AU
Note though that even though this is Kotlin's own extension method on String, it still only works on the JVM.
For those looking for a multiplatform implementation (as I was), mp_stools is one option.
I'm working on a multiplatform library with Kotlin
We need to display numbers with either "comma decimal " and "dot decimal" formats based on the locale
For example
-
1,00,000.50 for India , 1.00.00,50 for Europe
For this purpose I used Java's number format and Decimal format classes
DecimalFormat decim = new DecimalFormat("#,###.##"); tv.setText(decim.format(someFloat));
OR
NumberFormat.getInstance().format(my number) Both are good, but they are JAVA libraries won't work in KMM code
So, my question, is there any DecimalFormat and NumberFormat alternate libraires available for Kotlin Multiplatform ?
I don't like to use Expect / Actual implementation but a native ones
Remove last two # after . and add 00 in place of ##.
val dec = DecimalFormat("#,###,##0.00")
Example:
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.*;
public class AddZeroToOneDigitDecimal{
public static void main(String []args){
System.out.println(customFormat(3434));
System.out.println("----------");
System.out.println(customFormat(3434.34));
System.out.println("----------");
System.out.println(customFormat(3434.3));
}
public static String customFormat(double d){
String result = formatter.format(d);
return (result.replace(".00",""));
}
private static DecimalFormat formatter;
private static final String DECIMAL_FORMAT = "#,###,##0.00";
private static DecimalFormatSymbols formatSymbols = new DecimalFormatSymbols(Locale.ENGLISH);
static {
formatSymbols.setDecimalSeparator('.');
formatSymbols.setGroupingSeparator(' ');
formatter = new DecimalFormat(DECIMAL_FORMAT, formatSymbols);
}
}
Simplified
val formatter = DecimalFormat("#,###,##0.00");
return formatter.format(value).replace(".00","");