0

The default Java Float.toString(float) method prints a floating point number with "only as many ... [fractional] digits as are needed to uniquely distinguish the argument value from adjacent values of type float." Perfect! Just what I need---except that I need to do this in a locale-specific way (e.g. on a French computer "1.23" would be represented as "1,23").

How do I reproduce the functionality of Float.toString(float) in a locale-aware manner?

Garret Wilson
  • 18,219
  • 30
  • 144
  • 272

2 Answers2

0

You can try the following:

String s1 = String.format(Locale.FRANCE, "%.2f", 1.23f); // Country FRANCE 1,23
String s2 = String.format(Locale.FRENCH, "%.2f", 1.23f); // Language FRENCH 1,23
String s3 = String.format("%.2f", 1.23f); // Default Locale

.2 is optional and is the number of fractional digits

May works fine with the third if Locale.getDefault() return the appropriate Locale for France.

Another way is using NumberFormat

NumberFormat nf = NumberFormat.getInstance(Locale.FRENCH);
String s4 = nf.format(1.23f); // 1,23
Paul Vargas
  • 41,222
  • 15
  • 102
  • 148
0

I think that the important part of the question is that Float.toString() automatically figures out the number of decimal places that is relevant, and does a pretty good job of it. In my JRE, the class sun.misc.FloatingDecimal class is used. The logic in that class looks pretty complex and hard to reproduce.

Another class that can be used to guess the correct number of digits to display is BigDecimal. For example, if you are working with double rather than float:

double d = 1.23;
NumberFormat nf = NumberFormat.getNumberInstance(Locale.FRENCH); 
BigDecimal bd = BigDecimal.valueOf(d);
nf.setMaximumFractionDigits(bd.scale());
String s = nf.format(1.23f); // 1,23 

For floats, you first have to figure out how to convert from float to BigDecimal without changing the precision: How to convert from float to bigDecimal in java?

Community
  • 1
  • 1
Enwired
  • 1,563
  • 1
  • 12
  • 26