Thursday, December 12, 2019

5 Examples Of Formatting Float Or Double Numbers To String Inwards Java

Formatting floating dot numbers is a mutual chore inwards software evolution too Java programming is no different. You oft ask to pretty impress float too double values up-to 2 to 4 decimal places inwards console, GUI or JSP pages. Thankfully Java provides lots of convenient methods to format a floating dot release upwards to sure enough decimal places. For instance y'all tin purpose method printf() to format a float or double release to a output stream. However, it does non render a String. In JDK 1.5, a novel static method format() was added to the String class, which is similar to printf(), but returns a String. By the agency in that location are numerous agency to format numbers inwards Java, y'all tin purpose either DecimalFormat class, or NumberFormat or fifty-fifty Formatter class to format floating dot numbers inwards Java. Coming dorsum to String's format method, hither is a quick instance of using it :
String strDouble = String.format("%.2f", 1.23456);
This volition format the floating dot release 1.23456 up-to 2 decimal places, because nosotros accept used 2 afterward decimal dot inwards formatting pedagogy %.2f, f is for floating dot number, which includes both double and float data type inwards Java. Don't endeavor to purpose "d" for double here, because that is used to format integer too stands for decimal inwards formatting instruction. By the agency in that location is a choose handgrip of here, format() method volition likewise arbitrarily circular the number. For instance if y'all desire to format 1.99999 up-to 2 decimal places thence it volition render 2.0 rather than 1.99, equally shown below.


String strDouble = String.format("%.2f", 1.9999); System.out.println(strDouble); // impress 2.00



As I said before, this is non the alone agency to format floating dot numbers inwards Java, y'all tin purpose correct from the top Formatter class, which provides format() method similar to String's format() method. Alternatively, if y'all only desire to impress formatted floating dot numbers into console, y'all tin purpose System.printf() method, which effectively combine higher upwards 2 lines into unmarried one.

But the best method for chore is using DecmialFormat class, which is genuinely designed to format whatsoever release inwards Java live on it integer, float or double. While creating instance of DecimalFormat class, y'all tin top it a formatting string, which is chip dissimilar thence what y'all top to these format method, but I estimate its to a greater extent than readable. This string specifies up-to how many decimal places y'all desire to format the input. Here is a quick instance of formatting double too float numbers using DecimalFormat class.
DecimalFormat df = new DecimalFormat("#.##"); String formatted = df.format(2.456345);  System.out.println(formatted);  //prints 2.46
The string "#.##" indicate that nosotros are formatting up-to 2 decimal points, "#.###" indicates formatting release up-to three decimal places. By the way, fifty-fifty DecimalFormat rounds the number if side yesteryear side decimal dot is to a greater extent than than 5.

By the way, in that location is subtle departure betwixt formatting floating dot numbers using String.format() too DecimalFormat.format(), quondam volition always impress trailing zeros fifty-fifty if in that location is no fractional part. For instance if y'all format 2.00034 up-to 2 decimal places String's format() method volition impress "2.00", spell format() method of DecimalFormat class volition impress "2", equally shown below :
String strDouble = String.format("%.2f", 2.00023);   System.out.println(strDouble); // impress 2.00          DecimalFormat df = new DecimalFormat("#.##"); String formatted = df.format(2.00023);  System.out.println(formatted);  //prints 2
This is a real subtle but useful difference, its tardily to forget but pays good when y'all retrieve it. You tin similar a shot attain upwards one's heed what to purpose depending upon whether y'all ask trailing zeros or not.



Formatting Floating Point Number inwards Java

 Formatting floating dot numbers is a mutual chore inwards software evolution too Java progr v Examples of  Formatting Float or Double Numbers to String inwards Java
Here is our consummate Java programme to format floating dot numbers inwards Java. It includes all the ways, nosotros accept discussed thence far to format a float or double variable up-to sure enough decimal places inwards Java. You tin purpose whatsoever of these technique to pretty impress whatsoever float or double variable inwards Java. I personally similar to use DecimalFormat for its readability payoff but similar SimpleDateFormat, this is likewise an expensive object too non thread-safe, thence purpose this amongst caution. One to a greater extent than thing to consider is trailing zeros, if y'all desire trailing zeros e.g. desire to impress 2 equally "2.00" thence purpose String class' format method, otherwise purpose DecimalFormat's format method. Most of the fourth dimension y'all tin purpose a local instance of DecimalFormat, but if functioning is critical for your application thence y'all either ask to explicitly synchronize access of this object or purpose a ThreadLocal variable, which is to a greater extent than efficient, too avoids cost of acquiring too releasing locks. Now, it's fourth dimension to run into our code example.

import java.util.Arrays; import java.util.Formatter;   /** * Java programme to format float or double to String inwards Java. In this Java * example, y'all volition larn how to display a floating dot release up-to 2 or three * decimal places. * * @author Javin Paul */ public class FormatFloatInJava {       public static void main(String args[]) {           // First chore - format a floating dot release up-to 2 decimal places         float pi = 3.1428733f;           // From Java 5, String has a format() method         String str = String.format("%.02f", pi);         System.out.println("formatted float upwards to 2 decimals " + str);           // If y'all only desire to display, y'all tin combine higher upwards 2 yesteryear using printf()         // syntax of formatting volition rest same         // this volition display floating dot release up-to three decimals         System.out.printf("floating dot release up-to three decimals : %.03f %n", pi);           // Alternatively y'all tin likewise purpose Formatter shape to format floating dot numbers         // Allocate a Formatter on the StringBuilder         StringBuilder sb = new StringBuilder();         Formatter formatter = new Formatter(sb);  // Send all outputs to StringBuilder           // format() has the same syntax equally printf()         formatter.format("%.4f", pi);     // 4 decimal places         System.out.println("Value of PI upwards to 4 decimals : " + formatter.toString());         formatter.close();           // Similarly y'all tin format double to String inwards Java         double cost = 20.25;         System.out.printf("Value of double up-to 2 decimals : %.2f", price);          // best agency to format floating dot numbers inwards Java        // beware it likewise circular the numbers       DecimalFormat df = new DecimalFormat("#.##");       String formatted = df.format(2.456345);        System.out.println(formatted);  //prints 2.46      }   }   Output: formatted float up-to 2 decimals 3.14 floating dot release up-to three decimals : 3.143 Value of PI upwards to 4 decimals : 3.1429 Value of double up-to 2 decimals : 20.25 2.46

I only retrieve in that location is around other agency to pretty impress floating dot number inwards Java, yesteryear using setMaximumFractionDigits(int places) method shape NumberFormat class. y'all tin only top release of digit y'all desire to boot the bucket on decimals, for instance to format a release up-to 4 decimal places, top 4. Here is a quick instance of this :
double unproblematic = 4.0099; double circular = 4.9999; NumberFormat nf = NumberFormat.getInstance(); nf.setMaximumFractionDigits(3); System.out.println(nf.format(simple)); // prints 4.01 System.out.println(nf.format(round));  // prints 5

That's all close how to format floating dot numbers inwards Java. We accept seen next 4 ways to format a float or double release equally String inwards Java :

  1. By using String format() method
  2. By using DecimalFormat format() method
  3. By using printf() method 
  4. By using Formatter's format() method
  5. By using setMaximumFractionDigits() of NumberFormat class

You tin purpose whatsoever of these approaches to format floating dot numbers, only retrieve that String's format() volition e'er impress trailing zeros fifty-fifty if in that location is no to a greater extent than fractional part, spell DecimalFormat, NumberFormat classes will non boot the bucket on that. 

Further Learning
Data Structures too Algorithms: Deep Dive Using Java
Java Fundamentals: The Java Language
Complete Java Masterclass

No comments:

Post a Comment