-3

How can i remove the tailing zeros from the return of a function? Here is the function, which is in another class.

static public double Area(double side1,double side2){
    return side1*side2;
}

and here is the calling function

System.out.println("Side 1 : ");
b1=new Scanner(System.in);
double side1=b1.nextDouble();
System.out.println("Side 2: ");
b2=new Scanner(System.in);
double side2=b2.nextDouble();
System.out.println("Area= "+Rectangle.Area(side1, side2));

For side1=10 and side2=10 the output will be

Area = 100.0

while i want it to be

Area = 100

and for example for values 0.25 and 2 will be

Area = 0.5
  • 8
    Do you understand that there's no difference in representation between 100 and 100.0? It's like asking a method to return an `int` in hex instead of in decimal... it's just a number. (The very concept of "a trailing zero" only applies to `double` when you format it as a string. That's not the case for something like `BigDecimal` though.) – Jon Skeet Apr 11 '17 at 16:20
  • 5
    Trailing zeros is an artifact of how you display a value, it's not something that is stored as part of the value. Java != Cobol – azurefrog Apr 11 '17 at 16:21
  • If you want to drop those when outputting/converting to string: [*Format double value?*](http://stackoverflow.com/questions/24493051/java-format-double-value) – T.J. Crowder Apr 11 '17 at 16:24
  • If you want to chop off any fractional portion, use a `long`: `return (long)(side1*side2);` (changing the method signature as well). Or if you want to round it, `Math.round()`. – T.J. Crowder Apr 11 '17 at 16:30

2 Answers2

0

When you want to print a double, Java's printf and other similar features let you control issues including the number of digits, the use of the decimal separator, and the treatment of zero digits. More here: How to display an output of float data with 2 decimal places in Java?

Community
  • 1
  • 1
Aaron Mansheim
  • 425
  • 3
  • 11
0

You can use DecimalFormat to limit the decimals or drop trailing 0.

To limit decimals

double area = 0.1234;
DecimalFormat numberFormat = new DecimalFormat("#.00");
System.out.println(numberFormat.format(area));

It will give output as 0.12

You can use number of 0's as per requirement.

OR

System.out.printf("%.2f", area);

If you want to drop trailing 0 use #.# so 0.50 will be 0.5

DecimalFormat numberFormat = new DecimalFormat("#.#");