Math.round() not working properly

Killerpixler picture Killerpixler · Oct 2, 2012 · Viewed 8.2k times · Source

This is my program. very simply put, it is supposed to round an entered number to a given amount of decimals. I.e. 4.245 rounded to 2 decimals would give 4.25. However, I always only get it rounded to an integer back... Why? What is puzzling me is that I use the same code in android and it works flawlessly

import java.util.Scanner;


public class Rounder {

public static void main(String[] args) {
    double input1, roundednumber;
    int input2;
    Scanner keyboard = new Scanner(System.in);
    System.out.println("number to round ");
    input1 = keyboard.nextDouble();
    System.out.println("decimals");
    input2 = keyboard.nextInt();

    roundednumber = rounder(input1, input2);
    System.out.println(roundednumber);
}


public static double rounder(double number, int decimals){
    int multiplier = (int) Math.pow(10, decimals);
    double roundednumber;
    roundednumber = Math.round(number*multiplier)/multiplier;
    return roundednumber;       
}
}

And here is the snippet from my android class

double result1 = fv1/(Math.pow(1+(r1/n1),n1*t1));
result1 = (double) (Math.round(result1 * 100)) / 100;

Answer

Reimeus picture Reimeus · Oct 2, 2012

Dividing by an integer produces an integer, so you can use:

Math.round(number * multiplier) / (double)multiplier;