participate


New To Java - About decimal number!
<<   Back to Forum  |   Give us Feedback
This topic has 3 replies on 1 page.
sun26
Posts:9
Registered: 10/29/09
About decimal number!   
Nov 3, 2009 10:18 PM

 
Hi all,
I want to ask you a question:
If i have a method like this:
public double returnValue()
{
.........
return value;
}


=> how can i return value that has 6 figure-number after "."
Example 0.123456

Thanks!
 
jverd
Posts:51,846
Registered: 3/30/99
Re: About decimal number!   
Nov 3, 2009 10:44 PM (reply 1 of 3)  (In reply to original post )

 
You can't. Doubles don't have a format or a number of places after then decimal. All you can do is format it use java.text.DecimalFormat or String.format, or if you want fixed decimal precision, use BigDecimal.
 
amp88
Posts:87
Registered: 12/22/08
Re: About decimal number!   
Nov 3, 2009 11:53 PM (reply 2 of 3)  (In reply to #1 )

 
jverd wrote:
You can't. Doubles don't have a format or a number of places after then decimal. All you can do is format it use java.text.DecimalFormat or String.format, or if you want fixed decimal precision, use BigDecimal.

Yep, BigDecimal seems to be what you want. There is a time cost when using BigDecimal though, so keep that in mind if you do decide to use BigDecimal.

Example code:

package tester;
 
import java.math.BigDecimal;
 
public class BigDecimalExample {
	public static void main(String[] args) {
		new BigDecimalExample();
	}
	
	private BigDecimalExample() {
		double piDouble = 22/7.0;
		
		System.out.println("piDouble: "+piDouble);
		
		BigDecimal piTo2DecimalPlaces = new BigDecimal(piDouble);
		piTo2DecimalPlaces = piTo2DecimalPlaces.setScale(2, BigDecimal.ROUND_HALF_UP);
		
		System.out.println("piTo2DecimalPlaces: "+piTo2DecimalPlaces.doubleValue());
	}
}


Program output:

piDouble: 3.142857142857143
piTo2DecimalPlaces: 3.14
 
WalterLaan
Posts:816
Registered: 4/17/08
Re: About decimal number!   
Nov 4, 2009 7:26 AM (reply 3 of 3)  (In reply to #2 )

 
Probably you did it on purpose since 22/7 is on correct up to two decimals even though as double value is has more decimals.
double piDouble = Math.PI
// out piDouble: 3.141592653589793
 
This topic has 3 replies on 1 page.
Back to Forum
 
Read the Developer Forums Code of Conduct

Click to email this message Email this Topic

Edit this Topic
  
 
 
Forums Statistics
    Users Online : 29
  • Guests : 131

About Sun forums
  • Sun Forums is a large collection of user generated discussions. It is here to help you ask questions, find answers, and participate in discussions.

    Check out our guide on Getting started with Sun Forums for a full walkthrough of how to best leverage the benefits of this community.

Powered by Jive Forums