-2

In java: I have some number and a number of desired decimal places in a variable (e.g. choosen by user), and I need to print it.

myNumber = 3.987654;
numberOfDecimalPlaces = 4;

I dont want to do it like

System.out.printf( "%.4f", myNumber);

but I need to use VARIABLE numberOfDecimalPlaces instead.

Thanks a lot

MonikaV
  • 3
  • 2
  • 3
    Possible duplicate of [How to round a number to n decimal places in Java](http://stackoverflow.com/questions/153724/how-to-round-a-number-to-n-decimal-places-in-java) – InbetweenWeekends Nov 02 '15 at 15:03

3 Answers3

0

Just create the format string using numberOfDecimalPlaces:

System.out.printf( "%." + numberOfDecimalPlaces + 'f', myNumber);
wero
  • 31,694
  • 3
  • 55
  • 80
0

Can't understand why @wero is not a good answer but if you don't like to use System.out. maybe this..

NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(numberOfDecimalPlaces);
nf.setMinimumFractionDigits(numberOfDecimalPlaces);
String toPrint = nf.format(myNumber);
Petter Friberg
  • 20,644
  • 9
  • 57
  • 104
-1

You can try with this method :

//value is your input number and places for required decimal places

public static double function(double value, int places) {

    if (places < 0) {
        throw new IllegalArgumentException();
    }

    long factor = (long) Math.pow(10, places);
    value = value * factor;
    long tmp = Math.round(value);
    return (double) tmp / factor;
}
Madushan Perera
  • 2,578
  • 2
  • 16
  • 33