Formatting a Decimal Number to 2 Decimal Places in Java or JSP

F

I was looking around for the class to format a number to 2 decimal places while I was coding Java, or specifically JSP, and I found it.

First, you need to import the DecimalFormat class, so have this line at the top of your Java file:

import java.text.DecimalFormat;

Or if you’re running JSP:

<%@page import="java.text.DecimalFormat" %>

And here’s the actual code that does the magic:


double price = 10.59;
DecimalFormat priceFormatter = new DecimalFormat("$#0.00");
return priceFormatter.format(price);

That’s all there is to it! Simply change the Formatting string “$#0.00” to anything you wish. The pound (#) sign simply means there can be optional digits there. The two zero’s (0) to the right of the decimal place means that it has only 2 decimal places, and will be replaced by 0s if you don’t have digits there. Te $ sign right at the start is something that I put in, because I wanted to display my prices in dollars ($).

So for example, you can also have the formatting string as “#0.00 seconds more” and it’ll show “2343.36 seconds more”.

Similar Posts:

About the author

Alvin Poh

I've over 17 years of entrepreneurship experience, having built a tech company to be the top in the country, which was subsequently acquired for an 8-figure sum. As CEO, I led the company through robust growth to 150 employees across 4 countries. After the acquisition, I embraced minimalism, sold off my personal possessions, and started living around the world.

Read more about my story here.

2 comments

  • Hi Sir,
    I want to format a number in JSP
    Ex: if i have 10000 it should be displayed with number format as 10,000 and if its 1000000 it should be seperated by commas(,) as 1,00,000
    Pl mail me as soon as possible
    Regards
    Jaffer

  • To properly format a number with the comma separator (usually for thousands like you’ve mentioned), try this:

    System.out.printf( “%,.2f”, 12345678.9 );

    It returns 12,345,678.90

By Alvin Poh

About Author

I've over 17 years of entrepreneurship experience, having built a tech company to be the top in the country, which was subsequently acquired for an 8-figure sum. As CEO, I led the company through robust growth to 150 employees across 4 countries. After the acquisition, I embraced minimalism, sold off my personal possessions, and started living around the world.

Read more about my story here.