Logo 
Search:

Java Answers

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds
  Question Asked By: Jesse Black   on Apr 12 In Java Category.

  
Question Answered By: Ella Brown   on Apr 12

Here are 2 possible solutions. Please note that
rounder1() truncates the double  to the given
precision, whereas rouinder2() rounds it up or down.


public class RoundIt{
public string  rounder1(double d, double precision) {
String str = d+"";
System.out.println(str);
int point = str.indexOf(".");
str=str.substring(0,(point+(int)(precision+1)));
return str;
}

public double rounder2(double d, double precision) {
double d2= d*Math.pow(10,precision);
d2 = Math.rint(d2);
d2 /=Math.pow(10,precision);
return d2;
}

public static void main(String arg[]) {
RoundIt ri = new RoundIt();
double d1=7.123456789;
System.out.println(d1 +" " + ri.rounder1(d1, 2));
System.out.println(d1 +" " + ri.rounder2(d1, 3));
}
}

Share: 

 

This Question has 3 more answer(s). View Complete Question Thread

 
Didn't find what you were looking for? Find more on Rouning with double or float Or get search suggestion and latest updates.


Tagged: