Java Number Formatting

Java Number Formatting

Summary: At the end of this tutorial"Java Number Formatting", you will learn how to format numbers as you do in C/C++ with 0.2f format.

Formatting the number, the way user requires is known as number formatting. To write code for number formatting, the java.text package includes NumberFormat class. With this, the programmer can set the minimum and maximum fractional digits required in the output.

Program on Formatting Numbers

Following program guarantees the output for a minimum of 1 fractional digit and to a maximum of 3 fractional digits.

import java.text.*;   		// for NumberFormat
public class NumMat
  public static void main(String args[] )
    NumberFormat nf = NumberFormat.getInstance( );
    System.out.println(nf.format(10.0/3));  // prints 3.333
    System.out.println(nf.format(10/2));    //  prints 5.0	
    System.out.println(nf.format(7.6/2));   // prints 3.8
    System.out.println(nf.format(6.33/3));  // prints 2.11

Java Number Formatting
Output screen of of Java Number Formatting

Observe, the fractional value is set 1 to 3 (both inclusive). JVM gives if necessary only; for example, 7.6/2 prints 3.8 but not 3.800.

Check you java.lang IQ.

1. How many ways you can copy one object properties to another?
Ans: 3 ways – Shallow copying, Deep copying and Cloning.
2. How many types of inner classes exist?
Ans: 4 types.
3. What are JAR files?
Ans: JAR file is a zipped file zipped by JVM.
4. How to convert an object to string?
Ans: Object to String – toString()
5. What is the garbage collection mechanism in Java?
Ans: Garbage Collection – gc() and exit(0)
6. How to use the C++ destructor functionality where Java does not support destructors?
Ans: Java Destructor – finalize()
7. How to compare two objects?
Ans: Object comparison – hashCode() & equals()

Leave a Comment

Your email address will not be published.