

#Java string format code#
Note that the code not only trimmed the number down to two decimal places, but it also rounded the number. So if you run the code above, the output will look like this: 2 means "display the number in floating point format." That means exactly what you think it means: format the number to two decimal places. printf () uses the class to parse the format string and generate the output. () also prints a formatted string to the console. The text that follows the percent sign specifies the nature of the formatting. String.format () returns a formatted string. That first parameter, or the format specifier, always begins with a percent sign. The second parameter is the number itself. The first one is a String that describes how you want to format the number. I strongly recommend that you use java.time, the modern Java date and time API, for your date work. The format() method accepts two parameters. String to date format and vice versa java.time. That's accomplished with the format() static method that's part of the String class. Then you can display it as you see fit on the UI. Yeah, I'm using System.err instead of System.out because I always liked those red characters.Īnyhoo, the way to format the Double is to convert it to a formatted String. String formatted = String.format("%.2f", num) The following example shows the usage of () method. NullPointerException If the format is null. Let's say you've got the following number:Īnd you need to trim that bad boy down to two decimal spots. IllegalFormatException If a format string contains an illegal syntax, a format specifier that is incompatible with the given arguments, insufficient arguments given the format string, or other illegal conditions. You just need to display the Double with two or three decimal places.

Sometimes, especially in complex math operations, you end up with a Double that has enough numbers after the decimal point to fill the Grand Canyon.īut you don't need to show the user all those numbers. Then you can pick the option that best suits your business requirements.īecause I'm cool like that. In fact, I'll show you several ways to format that number.
#Java string format how to#
Got a Double object that you need to format for a UI? No problem, I'll show you how to do it here with String.format().
