0

I have a String representing a number (e.g. 1234.56) and a String representing a format (e.g. 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

1

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.