简体   繁体   中英

Formatting a number String according to format String

I have a String representing a number (eg 1234.56) and a String representing a format (eg 1,234.56 or 1 234.56 or 1234,56...) and need to format the number String according to the format String. Both Strings are given.

Some code for better underdstanding:

public static void main(String[] args) {
    String number = "1000.0";
    formatNumber(number, "1,234.56"); //Should be 1,000.00
    formatNumber(number, "1 234.56"); //Should be 1 000.00
    formatNumber(number, "1234,56"); //Should be 1000,00
}

public static String formatNumber(String number, String format) {
    return ???
}

Whats the best way to achieve that?

Thanks Paul

These three lines should do.

String pattern = format.replaceAll("\\d", "#");
DecimalFormat myFormatter = new DecimalFormat(pattern);
return myFormatter.format(value);

I am writing by heart, so write back if you encounter problems

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