简体   繁体   中英

android java : format numbers with different decimal separators

I am currently writing data using :

 ....
 for (int i = 0; i < 3; i++) { 
    data = data + ";" + String.format("%.8f", values.toArray()[i]); 
 }  
 ...
 captureFile.println( data );

but I need to changed the decimal separator based on a user's preference, not on Locale ( app is in english, but log analyzers can be using Excel french version...

if (decimalSeparatorDot) 
    // use current format ( US ) dot
else
    // String format with comma 

thanks for help

Is there a way to do it easily or should I change my String.format to a specific Formatter ?

I tried NumberFormat as following :

 NumberFormat nf;
 boolean dot = false;
 if (dot) {
  nf = NumberFormat.getInstance(Locale.US);
      ((DecimalFormat) nf).applyPattern("#0.00000000");

} else {
nf = NumberFormat.getInstance(Locale.FRENCH);
    ((DecimalFormat) nf).applyPattern("#0,00000000");           
}
...  
for (int i = 0; i < 3; i++) { data = data + ";" + nf.format(values.toArray()[i]); }

 it's working fine when dot is true ( current app Locale US ..) but it's giving all values to 0,000000000  when dot is false ( french)

don't know if it's the best way to do it , but it's working now using :

    NumberFormat nf= null;
    try {
        if (decimaSeparator == "dot") {
            nf = NumberFormat.getInstance(Locale.US);
            nf.setMinimumFractionDigits(8);
            nf.setMaximumFractionDigits(8);
        } else { // comma
            nf = NumberFormat.getInstance(Locale.FRENCH);
            nf.setMinimumFractionDigits(8);
            nf.setMaximumFractionDigits(8);
        }
    }
    catch (ClassCastException e) {
        System.err.println(e);
    }   

Try this..

DecimalFormat df = new DecimalFormat();
DecimalFormatSymbols dfs = new DecimalFormatSymbols();
dfs.setDecimalSeparator(','); // Set as dot or comma
df.setDecimalFormatSymbols(dfs);

Using Decimal Formatter:

val formatter = DecimalFormat().apply {
        val dfs = DecimalFormatSymbols().apply {
            decimalSeparator = ','
            groupingSeparator = '.'
        }
        decimalFormatSymbols = dfs
    }

    return formatter.format(value)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM