0

i am confuse about this problem.. a double value is given as input,such as 7.2 now output willbe 7.3 and 8. if input is 7.2.3 then output will be 7.2.4 and 7.3.3. i have tried below code so far

public class StrTest3 {
public static void main(String args[]){
    double num=0;
    double counter=0.0;
    Scanner sc=new Scanner(System.in);
    System.out.println("Enter number: ");
    num=sc.nextDouble();
    double num2=(double)Math.round(num);

}}

but its output for 7.2 is 7.0.. please help

mira nayak
  • 31
  • 2
  • possible duplicate of [String.format() to format double in java](http://stackoverflow.com/q/4885254/4454454) – MaxZoom Jun 04 '15 at 04:36

2 Answers2

1

The method

Math.round(double) 

returns a long, simply casting it to a double will not restore precision

As peer the javadocs

http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#round(double)

Returns the closest long to the argument, with ties rounding up

You could also try using NumberFormat

Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
0

You can be tricky in this case. Try,

num=num*10;
double new_num=((double)Math.round(num))/10;

This is a smarter way of achieving what you want. You can multiply and divide by the same number to set the decimal place up to which you want to round

Imesha Sudasingha
  • 3,462
  • 1
  • 23
  • 34