Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java String.format()

I have a string and I want to format it in a custom way.
This is my String:

String amount = "355128000";

I want it to be formatted like this way:

String formattedAMount = "3 551 280,00"

With a space after first number and a group of 3 numbers and a comma at the end before two nubmers

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can create an instance of NumberFormatter and specify options:

import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.Locale;

public class NumberFormatExample {

    private static final DecimalFormat numberFormatter;

    static {
        numberFormatter = (DecimalFormat) NumberFormat.getInstance(Locale.US);

        // Configure/override
        DecimalFormatSymbols symbols = numberFormatter.getDecimalFormatSymbols();
        symbols.setGroupingSeparator('\u00a0'); // non-breaking space
        symbols.setDecimalSeparator(',');
        numberFormatter.setDecimalFormatSymbols(symbols);
        numberFormatter.setMinimumFractionDigits(2);
    }

    public static String formatNumber(String rawNumber) {
        return numberFormatter.format(Long.parseLong(rawNumber) / 100d);
    }

    public static void main(String[] args) {
        String amount = "355128000";
        System.out.println(formatNumber(amount)); // 3 551 280,00
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading