String formatter java example7/21/2023 * Java program to format float or double to String in Java. Most of the time you can use a local instance of DecimalFormat, but if performance is critical for your application then you either need to explicitly synchronize access of this object or use a ThreadLocal variable, which is more efficient, and avoids cost of acquiring and releasing locks. You can now decide what to use depending upon whether you need trailing zeros or not. This is a very subtle but useful difference, its easy to forget but pays well when you remember it. println(strDouble) // print 2.00 DecimalFormat df = new DecimalFormat( "#.#") For example if you format 2.00034 up-to two decimal places String's format() method will print "2.00", while format() method of DecimalFormat class will print "2", as shown below : By the way, even DecimalFormat rounds the number if next decimal point is more than 5.īy the way, there is subtle difference between formatting floating point numbers using String.format() and DecimalFormat.format(), former will always print trailing zeros even if there is no fractional part. The string "#.#" indicate that we are formatting up-to 2 decimal points, "#.#" indicates formatting number up-to 3 decimal places. Here is a quick example of formatting double and float numbers using DecimalFormat class.ĭecimalFormat df = new DecimalFormat( "#.#") This string specifies up-to how many decimal places you want to format the input. While creating instance of DecimalFormat class, you can pass it a formatting string, which is bit different then what you pass to these format method, but I guess its more readable. Alternatively, if you just want to print formatted floating point numbers into console, you can use System.printf() method, which effectively combine above two lines into single one.īut the best method for task is using DecmialFormat class, which is actually designed to format any number in Java be it integer, float or double. println(strDouble) // print 2.00Īs I said before, this is not the only way to format floating point numbers in Java, you can use right from the top Formatter class, which provides format() method similar to String's format() method. For example if you want to format 1.99999 up-to 2 decimal places then it will return 2.0 rather than 1.99, as shown below. String title 'Effective Java' float price 33.953f ('s is a great book.
0 Comments
Leave a Reply. |