This week's book giveaway is in the Cloud/Virtualization forum.We're giving away four copies of Building Blockchain Apps and have Michael Yuan on-line!See this thread for details.
Win a copy of Building Blockchain Apps this week in the Cloud/Virtualization forum!
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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Paul Clapham
• Liutauras Vilda
• Knute Snortum
• Bear Bibeault
Sheriffs:
• Devaka Cooray
• Jeanne Boyarsky
• Junilu Lacar
Saloon Keepers:
• Ron McLeod
• Stephan van Hulst
• Tim Moores
• Carey Brown
• salvin francis
Bartenders:
• Tim Holloway
• Piet Souris
• Frits Walraven

# Round off a value

Greenhorn
Posts: 19
Hi

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

Seb

Ranch Hand
Posts: 65
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

Marshal
Posts: 67366
173
Not really a JSP question so moving along to the Java Intermediate forum.

Ranch Hand
Posts: 3061

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
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

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.