-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
  • 32,544
  • 3
  • 59
  • 84
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
  • 21,252
  • 9
  • 60
  • 109
-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,568
  • 2
  • 17
  • 36