0

I have this code:

import java.util.Scanner;

public class DecimalPoints {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) 
    {
        Scanner scanner = new Scanner(System.in);

        System.out.println("a: ");               // printing output
        String text_1 = scanner.nextLine();      // taking input
        double d1 = Double.parseDouble(text_1);  // parsing double from input  

        System.out.println("b: ");               // printing output
        String text_2 = scanner.nextLine();      // taking input
        double d2 = Double.parseDouble(text_2);  // parsing double from input

        double d3 = d1 / d2;

        d3 = Math.round(d3 * 100) / 100.0d;

        System.out.println("Result: " + d3);
    }
}

It takes two inputs and rounds it up to two decimal places but the problem is that it rounds up the result. Let's say that I enter a = 513 and b = 791 the result would be 0.65 but when I check my calculator it shows me 0.648...Does anyone know how to leave the number just at 0.64? Much Obliged.

informatik01
  • 15,174
  • 9
  • 67
  • 100
user2529011
  • 557
  • 3
  • 7
  • 17
  • What do you want it to do if `d3` is negative? – Dawood ibn Kareem Nov 04 '13 at 00:06
  • no... d3 works just fine I just want d3 to spit out the result without rounding the number up for instance if 513 is divided by 791 I want ti to display 0.64 and not 0.65. Get it now? – user2529011 Nov 04 '13 at 00:08
  • 1
    My question was to work out whether you wanted to round ALWAYS DOWNWARDS (like `Math.floor` does) or always TOWARDS ZERO (like just dropping the decimals off the number, which seemed to be closer to your description). They are different if `d3` is negative. Repeating what you had already said didn't really cover the case that you had omitted. – Dawood ibn Kareem Nov 04 '13 at 02:06

2 Answers2

5

Maybe use Math.floor() instead of Math.round()?

yyoon
  • 2,400
  • 3
  • 17
  • 17
0

Check out java.math.BigDecimal.

e_r
  • 744
  • 2
  • 8
  • 18