We help IT Professionals succeed at work.

# Precision

on
Medium Priority
350 Views
public class Square
{
public static void main (String args[])
{
System.out.println("Square is : " + 1.13*1.13);
}
}

How is the normal implementation to tackle with such problem of precion?
Comment
Watch Question

## View Solution Only

Commented:
> java Square

Square is : 1.2769

what's the problem ?
Commented:
Hi kenchan2000,

Usual way for tackel precision is Use java.math package.
i.e. use BigInteger or BigDecimal class. It allow U to round the values to your requried position.
Generic Example:

/*********************** code ***************************

import java.math.*;
public class Square
{
public static void main (String args[])
{
double val = 1.13;
int denominator = 1;
int precision=3;
System.out.println("Square is : " + val * val);
try {
BigDecimal bigDinom = new BigDecimal(denominator);
BigDecimal doubleVal = new BigDecimal(val);
doubleVal = doubleVal.divide(bigDinom,precision,doubleVal.ROUND_HALF_DOWN);
System.out.println("Square is: Of BigDecimal " + doubleVal);
val = doubleVal.doubleValue();
System.out.println("Square is: Double " + val);
} catch(ArithmeticException ae){
System.out.println("Err" + ae.getMessage());
}
}
}

/********************* End code **************************