Saturday, December 27, 2008

Setting Decimal Precision

Here is a simple program that is used to set the precision digits in for a floating point number.

This program was created in Eclipse using the jdk 5.0.

//-----------Program code begins here-------------

import java.text.NumberFormat;

public class SetPrecision {

public static void main(String args[])
//A sample float number.
float anumber= 100.12345678F;

//Creating a NumberFormat object that will used to
//format a number.
NumberFormat nf= NumberFormat.getInstance();

//Setting the number of digits that are required to be
//printed after the decimal point.

//Formatting the number returns a string object.
String truncatedNumberString=nf.format(anumber);

//Parsing the string into a float using a
//Wrapper class function - Float.parseFloat
float truncatedNumber=Float.parseFloat(truncatedNumberString);



//-----------Program code Ends here-------------

Signing off

No comments: