Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

Rouning with double or float

  Asked By: Jesse    Date: Apr 12    Category: Java    Views: 955
  

When appending a float or double value to a string, how can I
truncate/round the number to a certain number of digits?

For example
double x = 7.00000001;
String y = "x * ";

y += x;

will result in
y = "x * 7.00000001"
how do I mke is so that it will be
y = "x * 7.0"

Share: 

 

4 Answers Found

 
Answer #1    Answered By: Della Simpson     Answered On: Apr 12

I think you can convert the native data type double  to
a Java object Double (there is a constructor for that)
and apply different formats or truncation methods. You
can search in the API for Double class reference and
methods.

http://java.sun.com/j2se/1.4.2/docs/api/

 
Answer #2    Answered By: Devrim Yilmaz     Answered On: Apr 12

Check out java.text.NumberFormat.

 
Answer #3    Answered By: Ella Brown     Answered 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));
}
}

 
Answer #4    Answered By: Liam Bouchard     Answered On: Apr 12

while this is an interesting way to do rounding, it's a *tad* inefficient.
It's as if you're reinventing the wheel by making one the size of a house. If
you want to round just use DecimalFormat:

import java.text.DecimalFormat;
public class Rounding {
public static void main(String[] args) {
DecimalFormat df = new DecimalFormat("#.00");
double d = 3.12345678901;
System.out.println(df.format(d));
}
}

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




Tagged: