programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Devaka Cooray
• Ron McLeod
• Paul Clapham
• Liutauras Vilda
Sheriffs:
• paul wheaton
• Jeanne Boyarsky
• Tim Cooke
Saloon Keepers:
• Stephan van Hulst
• Tim Holloway
• Tim Moores
• Mikalai Zaikin
• Carey Brown
Bartenders:

# Round off a value

Greenhorn
Posts: 19
• Number of slices to send:
Optional 'thank-you' note:
Hi

How do we round off a value to 6 decimal places and display it in a jsp?

Seb

Ranch Hand
Posts: 65
• Number of slices to send:
Optional 'thank-you' note:
Hi seb,

Get the value in to one float or double depand upon the value. import the util.* in the jsp page and use the desired function to round of the value .

Float f ;
f= 12.546465469546f;
Know the f value using the round function in java.util pack
i think this can help you.

Sheriff
Posts: 67735
173
• Number of slices to send:
Optional 'thank-you' note:
Not really a JSP question so moving along to the Java Intermediate forum.

Ranch Hand
Posts: 3061
• Number of slices to send:
Optional 'thank-you' note:

Originally posted by Christie George:
Hi

How do we round off a value to 6 decimal places and display it in a jsp?

Seb

Since you are doing this for display purposes, you should probably use java.text.NumberFormat. This class has methods to specify the number of digits before and after the decimal point. See the above link to the appropriate Javadocs for details.

Layne

Greenhorn
Posts: 22
• Number of slices to send:
Optional 'thank-you' note:
There is a little trick - you multiply by 10^n where n is the number of decimal points you want, add 0.5, take integer, and divide result by 10^n. E.g. try this,

public class Rounder {
public static void main(String[] args) {
double n = 6; //no. of decimal places
double x = 123.12345678901234; //no. to be rounded
double y = (int)(x*Math.pow(10,n)+0.5)/Math.pow(10,n);
System.out.println(y); //result
}
}

Hope this helps,
Alastair

Ranch Hand
Posts: 1646
• Number of slices to send:
Optional 'thank-you' note:

Originally posted by Alastair Calderwood:
There is a little trick...

Since float and double values are not stored in decimal notation, they are only approximations of decimal values. While this trick will get you close, it won't be exact.

If you just want to round for display, use NumberFormat Layne said. If you need to use the rounded number in an exact calculation, you should use java.math.BigDecimal. The latter represents an exact decimal value to a very high number of decimal places and precision.

 I'm not sure if I approve of this interruption. But this tiny ad checks out: a bit of art, as a gift, the permaculture playing cards https://gardener-gift.com
reply
Similar Threads