Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format Double with dot?

How do I format a Double with String.format to String with a dot between the integer and decimal part?

String s = String.format("%.2f", price); 

The above formats only with a comma: ",".

like image 999
Shikarn-O Avatar asked Mar 03 '11 15:03

Shikarn-O


People also ask

How do I format a double string?

Just use %. 2f as the format specifier. This will make the Java printf format a double to two decimal places. /* Code example to print a double to two decimal places with Java printf */ System.

How to remove decimal point in double value?

Truncation Using Casting If our double value is within the int range, we can cast it to an int. The cast truncates the decimal part, meaning that it cuts it off without doing any rounding.

How to print 2 zeros after decimal in Java?

To be able to print any given number with two zeros after the decimal point, we'll use one more time DecimalFormat class with a predefined pattern: public static double withTwoDecimalPlaces(double value) { DecimalFormat df = new DecimalFormat("#. 00"); return new Double(df.


2 Answers

String.format(String, Object ...) is using your JVM's default locale. You can use whatever locale using String.format(Locale, String, Object ...) or java.util.Formatter directly.

String s = String.format(Locale.US, "%.2f", price); 

or

String s = new Formatter(Locale.US).format("%.2f", price); 

or

// do this at application startup, e.g. in your main() method Locale.setDefault(Locale.US);  // now you can use String.format(..) as you did before String s = String.format("%.2f", price); 

or

// set locale using system properties at JVM startup java -Duser.language=en -Duser.region=US ... 
like image 183
sfussenegger Avatar answered Oct 08 '22 20:10

sfussenegger


Based on this post you can do it like this and it works for me on Android 7.0

import java.text.DecimalFormat import java.text.DecimalFormatSymbols  DecimalFormat df = new DecimalFormat("#,##0.00"); df.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.ITALY)); System.out.println(df.format(yourNumber)); //will output 123.456,78 

This way you have dot and comma based on your Locale

Answer edited and fixed thanks to Kevin van Mierlo comment

like image 29
Ultimo_m Avatar answered Oct 08 '22 22:10

Ultimo_m