0
private static double round (double value, int precision) {
    int scale = (int) Math.pow(10, precision);
    return (double) Math.round(value * scale) / scale;
}

I would like this code to not only be able to round to any given decimal place, but also to either always round up or down, this could be given as another paramter. But I am having trouble with how to implement this.

For example, I want to round 11.1436 to 11.15. Please help.

Ulsting
  • 301
  • 2
  • 4
  • 15

1 Answers1

-1

like you said you have to use math ceil to round up ,so you can pass true if you want to round up or you can pass false to round it down you could use

math.floor-->round down
math.ceil -->round up 

instead math.round

private static double round (double value, int precision,boolean up) {
int scale = (int) Math.pow(10, precision);
if(up){
    return (double) Math.ceil(value * scale) / scale;
}else{
   return (double) Math.floor(value * scale) / scale;
}

output>>

 System.out.println(round(11.1436, 2,true)); --> 11.15 //up
 System.out.println(round(11.1436, 2,false)); --> 11.14 //down
Madhawa Priyashantha
  • 9,208
  • 7
  • 28
  • 58
  • to be consistent, I'd probably use Math.floor(...) instead of Math.round(...) That way, you can truly round down when up = false. – smertrios Oct 16 '14 at 02:07
  • @smertrios yes i think Math.floor is definitely round down while math.round can up or down.so i edited it – Madhawa Priyashantha Oct 16 '14 at 02:11
  • This doesn't really round to a specific number of decimal places. Floating point variables don't have decimal places. See the duplicated question. – user207421 Oct 16 '14 at 02:31
  • @getlost 1. The question contains the words 'round to a certain decimal place' and 'round to any given decimal place'. 2. *Ergo* I have read the question. 3. There is no 'yelling here': flagged as offensive. – user207421 Oct 16 '14 at 02:46
  • should i care about your steps – Madhawa Priyashantha Oct 16 '14 at 17:45