How many decimal Places in A Double (Java)check if double/float has more than 2 decimal numberHow do I check whether a double variable has more than two decimals in Java?multiplying using + and - in javaHow to solve this rounding requirement?DecimalFormat - Format decimal to preserve variable amount of trailing zerosHow can I output localized Java floating point values in full precision?Is Java “pass-by-reference” or “pass-by-value”?How do I efficiently iterate over each entry in a Java Map?How to round a number to n decimal places in JavaFastest way to determine if an integer's square root is an integerHow do I read / convert an InputStream into a String in Java?How do I generate random integers within a specific range in Java?Limiting floats to two decimal pointsHow do I convert a String to an int in Java?Creating a memory leak with JavaRound to at most 2 decimal places (only if necessary)
Is there a way to hide HTML source code yet keeping it effective?
Would the same counter be used for a slice of pizza and a whole one?
Two trains move towards each other, a bird moves between them. How many trips can the bird make?
Could Apollo astronauts see city lights from the moon?
How to deal with a Homophobic PC
What's the next step in this Unequal (Futoshiki) puzzle?
Norwegian refuses EU delay (4.7 hours) compensation because it turned out there was nothing wrong with the aircraft
Designing a time thief proof safe
Safely hang a mirror that does not have hooks
Is it a good idea to leave minor world details to the reader's imagination?
What is the need of methods like GET and POST in the HTTP protocol?
Is there any iPhone SE out there with 3D Touch?
Going to France with limited French for a day
Does wetting a beer glass change the foam characteristics?
What benefits does the Power Word Kill spell have?
Organisational search option
Does Sitecore have support for Sitecore products in containers?
1, 2, 4, 8, 16, ... 33?
I reverse the source code, you negate the input!
Why is there not a feasible solution for a MIP?
What did Tim Curry say in the movie Congo to Ernie Hudson after being insulted?
Is it possible to encode a message in such a way that can only be read by someone or something capable of seeing into the very near future?
Is it really necessary to have a four hour meeting in Sprint planning?
Examples of "unsuccessful" theories with afterlives
How many decimal Places in A Double (Java)
check if double/float has more than 2 decimal numberHow do I check whether a double variable has more than two decimals in Java?multiplying using + and - in javaHow to solve this rounding requirement?DecimalFormat - Format decimal to preserve variable amount of trailing zerosHow can I output localized Java floating point values in full precision?Is Java “pass-by-reference” or “pass-by-value”?How do I efficiently iterate over each entry in a Java Map?How to round a number to n decimal places in JavaFastest way to determine if an integer's square root is an integerHow do I read / convert an InputStream into a String in Java?How do I generate random integers within a specific range in Java?Limiting floats to two decimal pointsHow do I convert a String to an int in Java?Creating a memory leak with JavaRound to at most 2 decimal places (only if necessary)
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
Is there any in built function in java to tell me how many decimal places in a double. For example:
101.13 = 2
101.130 = 3
1.100 = 3
1.1 = 1
-3.2322 = 4 etc.
I am happy to convert to another type first if needed, I have looked at converting to bigdecimal first with no luck.
java rounding
add a comment
|
Is there any in built function in java to tell me how many decimal places in a double. For example:
101.13 = 2
101.130 = 3
1.100 = 3
1.1 = 1
-3.2322 = 4 etc.
I am happy to convert to another type first if needed, I have looked at converting to bigdecimal first with no luck.
java rounding
add a comment
|
Is there any in built function in java to tell me how many decimal places in a double. For example:
101.13 = 2
101.130 = 3
1.100 = 3
1.1 = 1
-3.2322 = 4 etc.
I am happy to convert to another type first if needed, I have looked at converting to bigdecimal first with no luck.
java rounding
Is there any in built function in java to tell me how many decimal places in a double. For example:
101.13 = 2
101.130 = 3
1.100 = 3
1.1 = 1
-3.2322 = 4 etc.
I am happy to convert to another type first if needed, I have looked at converting to bigdecimal first with no luck.
java rounding
java rounding
edited Nov 28 '12 at 13:31
Artemix
1,6482 gold badges20 silver badges30 bronze badges
1,6482 gold badges20 silver badges30 bronze badges
asked Jul 26 '10 at 10:57
KarlKarl
1,8648 gold badges24 silver badges35 bronze badges
1,8648 gold badges24 silver badges35 bronze badges
add a comment
|
add a comment
|
7 Answers
7
active
oldest
votes
No.
1.100 and 1.1 are exactly the same value (they are represented exactly the same bit-for-bit in a double
).
Therefore you can't ever get that kind of information from a double
.
The only thing you can do is to get the minimum number of decimal digits necessary for a decimal number to be parsed into the same double
value. And that is as easy as calling Double.toString()
and checking how many decimal digits there are.
1
Calling toString() seems a little shakey but was my initial thought.
– Karl
Jul 26 '10 at 11:05
1
@Karl: it is shaky, but possibly the best thing you can do. It breaks for very large and very small values (as you'll get scientific notation). The only 100% correct solution is to do that test when you have the value as aString
before you convert it to adouble
(as Andrei demonstrates).
– Joachim Sauer
Jul 26 '10 at 11:19
add a comment
|
You could use BigDecimal.scale() if you pass the number as a String like this:
BigDecimal a = new BigDecimal("1.31");
System.out.println(a.scale()); //prints 2
BigDecimal b = new BigDecimal("1.310");
System.out.println(b.scale()); //prints 3
but if you already have the number as string you might as well just parse the string with a regex to see how many digits there are:
String[] s = "1.31".split("\.");
System.out.println(s[s.length - 1].length());
Using BigDecimal might have the advantage that it checks if the string is actually a number; using the string method you have to do it yourself. Also, if you have the numbers as double you can't differentiate between 1.31
and 1.310
(they're exactly the same double) like others have pointed out as well.
add a comment
|
The number of decimal places in a double is 16.
64-bit numbers. 52-bit Mantissa. 52 bits is about 16 decimal digits.
See http://java.sun.com/docs/books/jls/second_edition/html/typesValues.doc.html.
double, whose values include the 64-bit IEEE 754 floating-point numbers.
See http://en.wikipedia.org/wiki/IEEE_754-2008
2
No, that's the number of decimal digits, and it's wrong, it is 15.9. Consider "123456789012345". Fifteen decimal digits, zero decimal places. "12345678901234.5". Fifteen decimal digits, one decimal place. Etc.
– user207421
Jul 27 '10 at 4:08
3
@EJP: I would think that 15.9 is "About 16". It appears from your comment that you don't think 15.9 is "about 16". If you want to claim 15.9 is not "about 16", then you're wrong also, since it's not 15.9, either. Wikipedia says "17 decimal digits" and 15.955 digits.
– S.Lott
Jul 27 '10 at 9:59
4
@EJP: Please read the IEEE standard carefully. In particular, read about the implicit bits in the significand.
– S.Lott
Jul 27 '10 at 11:31
3
OK, we are just quibbling here, but it is 15.9545897701910000. To 16 decimal places ;-)
– user207421
Jul 28 '10 at 2:58
2
OK. I am quibbling.
– user207421
Jul 28 '10 at 10:50
|
show 4 more comments
No, there is no built-in function that I know about.
There is a simple way to do this, though. Double.toString will give you a string containing ALL significant decimal digits in the double. The following are some properties of that string:
- The String that results may be in decimal notation or scientific
notation, depending on the value of the double. - Doubles that convert to decimals 10,000,000 or larger or smaller than
1/1000 result in scientific notation. Otherwise, they are in decimal
notation.
Using Double.toString to figure out how many decimal places there are essentially comprises how many significant digits to the right of the decimal point minus a scientific notation exponent, if there is one. Decimal notation will always have at least one digit to the right of the decimal point, and at least one digit to the left of the decimal point, even if it is a zero. Since we are concerned about decimal places for significant digits, a trailing zero to the right of the decimal point is a concern and should not be counted as a decimal place.
The following code will make a good calculation for you:
StringBuffer stringBuffer = new StringBuffer(Double.toString(1234.567890D));
System.out.println(stringBuffer.toString());
int i; // general purpose character index
int exponent;
int decimalPlaces;
if ((i = stringBuffer.indexOf("E")) > -1) // scientific notation...
// turn scientific notation exponent into an integer
exponent = Integer.parseInt(stringBuffer.substring(i + 1));
// truncate the exponent from the StringBuffer
stringBuffer = stringBuffer.delete(i, stringBuffer.length());
else // decimal notation, could be trailing zero
exponent = 0; // no exponent, so zero
// point i to trailing zero and truncate it, if there is one
if (stringBuffer.charAt((i = stringBuffer.length() - 1)) == '0')
stringBuffer = stringBuffer.deleteCharAt(i); // delete trailing zero
// stringBuffer now contains only significant digits to the
// right of the decimal point, if there are any
decimalPlaces = stringBuffer.length() - 1 - stringBuffer.indexOf(".") - exponent;
// zero or positive number is decimal places
// negative number is number of zeroes to the left of the decimal point
// between the decimal point and the least significant digit
System.out.println(decimalPlaces);
I have some questions about the question posed. What kind of precision is expected with the decimal representation of a double? Are doubles being used to inappropriately perform decimal computations? Decimal computations with decimal fractions using floats and doubles can have results that unexpectedly have 16 or 17 significant digits and may be only approximations of the expected results from equivalent decimal computations.
One aspect of float, doubles, long doubles (aka quads) that seems to stymie programmers and designers is that all these formats are actually stored as binary fractional numbers that can only approximate decimal numbers except for a very, very few numbers, most of which are fairly close to the values 1, -1, plus the value zero. As one progresses towards positive infinity or zero from 1, or towards negative infinity or zero from -1, the sparseness of the approximation will become apparent.
Almost all decimal fractions have no direct representation in floats and doubles. Only decimal fractions that can be comprised from the sum of some combination of the following series of fractions have an exact representation:
1, 1/2, 1/4, 1/8, 1/16, 1/32, 1/64, 1/128, 1/256, ..., 1/4503599627370496
All the rest are approximations.
Integers greater than +9007199254740992 or less than -9007199254740992 may not have an exact representation and the sparseness increases exponentially as integers increase above the positive or decrease below the negative values, respectively.
Another way to look at this is to realize that IEEE 64-bit doubles, normalized, approximate positive and negative decimal numbers having absolute values ranging from 2.225073858507201400 E -308 through 1.797693134862315700 E +308. However, there are only 1.8446744073709551616 E +19 values available for these approximations. That means about 1.0 E +607 decimal values share a representation with some other decimal values that are more closely approximated by a double.
The behavior of floats and doubles wrecks havoc with decimal computations requiring exact decimal accuracy, such as financial calculations and is why, unless a high-precision approximation is acceptable, one should use scaled integers and longs, or classes such as BigInteger and BigDecimal, for computations requiring exact decimal accuracy, rounding and precision.
add a comment
|
// ****************************************************************
public int getDecimals(double doubleValue)
// ****************************************************************
BigDecimal bd1 = new BigDecimal(Double.toString(doubleValue)).stripTrailingZeros();
return bd1.scale();
The toString part is crucial.
– David I.
May 6 '14 at 15:39
add a comment
|
From many long years ago, I recall an answer of 16 digits, total of before and after the decimal point.
I wrote a tiny bit of code to test that.
public class test
public static void main(String[] args)
double x;`enter code here`
x = 3411.999999999999;
System.out.println("16: "+x); // gives 3411.999999999999
x = 3411.9999999999999;
System.out.println("17: "+x); // gives 3412.0
x = 0.9999999999999999;
System.out.println("16: "+x); // gives 0.9999999999999999
x = 0.99999999999999999;
System.out.println("17: "+x); // gives 1.0
There 4+12 = 16 digits. A run outputs 3411.999999999999.
Now add one more 9 behind the decimal point for a total of 17 - 3411.9999999999999 - and rerun. The value printed is 3412.0. In this case, we overload the internal representation of x, and the number is rounded internally to store.
The println faithfully prints what it sees internally. There are only so many bits - 64 to be exact - to hold the double floating number (significand and exponent - see IEEE 754 for the gory details).
Play around with the value of x and you'll see the effects. For instance, 0.9999999999999999 (16 9s)give output 0.9999999999999999; 0.99999999999999999 (17 9s) gives 1.0.
Hope this helps.
add a comment
|
StringBuffer stringBuffer = new StringBuffer(Double.toString(ratioGrossYield));
int i; // general purpose character index
int exponent;
int decimalPlaces;
if ((i = stringBuffer.indexOf("E")) > -1) // scientific notation...
// turn scientific notation exponent into an integer
exponent = Integer.parseInt(stringBuffer.substring(i + 1));
// truncate the exponent from the StringBuffer
stringBuffer = stringBuffer.delete(i, stringBuffer.length());
else // decimal notation, could be trailing zero
exponent = 0; // no exponent, so zero
// point i to trailing zero and truncate it, if there is one
if (stringBuffer.charAt((i = stringBuffer.length() - 1)) == '0')
stringBuffer = stringBuffer.deleteCharAt(i); // delete trailing zero
// stringBuffer now contains only significant digits to the
// right of the decimal point, if there are any
decimalPlaces = stringBuffer.length() - 1 - stringBuffer.indexOf(".") - exponent;
// zero or positive number is decimal places
// negative number is number of zeroes to the left of the decimal point
// between the decimal point and the least significant digit
if (stringBuffer.charAt(stringBuffer.length() - 1) == '0')
return decimalPlaces-1;
else
return decimalPlaces;
add a comment
|
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f3334168%2fhow-many-decimal-places-in-a-double-java%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
7 Answers
7
active
oldest
votes
7 Answers
7
active
oldest
votes
active
oldest
votes
active
oldest
votes
No.
1.100 and 1.1 are exactly the same value (they are represented exactly the same bit-for-bit in a double
).
Therefore you can't ever get that kind of information from a double
.
The only thing you can do is to get the minimum number of decimal digits necessary for a decimal number to be parsed into the same double
value. And that is as easy as calling Double.toString()
and checking how many decimal digits there are.
1
Calling toString() seems a little shakey but was my initial thought.
– Karl
Jul 26 '10 at 11:05
1
@Karl: it is shaky, but possibly the best thing you can do. It breaks for very large and very small values (as you'll get scientific notation). The only 100% correct solution is to do that test when you have the value as aString
before you convert it to adouble
(as Andrei demonstrates).
– Joachim Sauer
Jul 26 '10 at 11:19
add a comment
|
No.
1.100 and 1.1 are exactly the same value (they are represented exactly the same bit-for-bit in a double
).
Therefore you can't ever get that kind of information from a double
.
The only thing you can do is to get the minimum number of decimal digits necessary for a decimal number to be parsed into the same double
value. And that is as easy as calling Double.toString()
and checking how many decimal digits there are.
1
Calling toString() seems a little shakey but was my initial thought.
– Karl
Jul 26 '10 at 11:05
1
@Karl: it is shaky, but possibly the best thing you can do. It breaks for very large and very small values (as you'll get scientific notation). The only 100% correct solution is to do that test when you have the value as aString
before you convert it to adouble
(as Andrei demonstrates).
– Joachim Sauer
Jul 26 '10 at 11:19
add a comment
|
No.
1.100 and 1.1 are exactly the same value (they are represented exactly the same bit-for-bit in a double
).
Therefore you can't ever get that kind of information from a double
.
The only thing you can do is to get the minimum number of decimal digits necessary for a decimal number to be parsed into the same double
value. And that is as easy as calling Double.toString()
and checking how many decimal digits there are.
No.
1.100 and 1.1 are exactly the same value (they are represented exactly the same bit-for-bit in a double
).
Therefore you can't ever get that kind of information from a double
.
The only thing you can do is to get the minimum number of decimal digits necessary for a decimal number to be parsed into the same double
value. And that is as easy as calling Double.toString()
and checking how many decimal digits there are.
answered Jul 26 '10 at 11:00
Joachim SauerJoachim Sauer
247k50 gold badges494 silver badges568 bronze badges
247k50 gold badges494 silver badges568 bronze badges
1
Calling toString() seems a little shakey but was my initial thought.
– Karl
Jul 26 '10 at 11:05
1
@Karl: it is shaky, but possibly the best thing you can do. It breaks for very large and very small values (as you'll get scientific notation). The only 100% correct solution is to do that test when you have the value as aString
before you convert it to adouble
(as Andrei demonstrates).
– Joachim Sauer
Jul 26 '10 at 11:19
add a comment
|
1
Calling toString() seems a little shakey but was my initial thought.
– Karl
Jul 26 '10 at 11:05
1
@Karl: it is shaky, but possibly the best thing you can do. It breaks for very large and very small values (as you'll get scientific notation). The only 100% correct solution is to do that test when you have the value as aString
before you convert it to adouble
(as Andrei demonstrates).
– Joachim Sauer
Jul 26 '10 at 11:19
1
1
Calling toString() seems a little shakey but was my initial thought.
– Karl
Jul 26 '10 at 11:05
Calling toString() seems a little shakey but was my initial thought.
– Karl
Jul 26 '10 at 11:05
1
1
@Karl: it is shaky, but possibly the best thing you can do. It breaks for very large and very small values (as you'll get scientific notation). The only 100% correct solution is to do that test when you have the value as a
String
before you convert it to a double
(as Andrei demonstrates).– Joachim Sauer
Jul 26 '10 at 11:19
@Karl: it is shaky, but possibly the best thing you can do. It breaks for very large and very small values (as you'll get scientific notation). The only 100% correct solution is to do that test when you have the value as a
String
before you convert it to a double
(as Andrei demonstrates).– Joachim Sauer
Jul 26 '10 at 11:19
add a comment
|
You could use BigDecimal.scale() if you pass the number as a String like this:
BigDecimal a = new BigDecimal("1.31");
System.out.println(a.scale()); //prints 2
BigDecimal b = new BigDecimal("1.310");
System.out.println(b.scale()); //prints 3
but if you already have the number as string you might as well just parse the string with a regex to see how many digits there are:
String[] s = "1.31".split("\.");
System.out.println(s[s.length - 1].length());
Using BigDecimal might have the advantage that it checks if the string is actually a number; using the string method you have to do it yourself. Also, if you have the numbers as double you can't differentiate between 1.31
and 1.310
(they're exactly the same double) like others have pointed out as well.
add a comment
|
You could use BigDecimal.scale() if you pass the number as a String like this:
BigDecimal a = new BigDecimal("1.31");
System.out.println(a.scale()); //prints 2
BigDecimal b = new BigDecimal("1.310");
System.out.println(b.scale()); //prints 3
but if you already have the number as string you might as well just parse the string with a regex to see how many digits there are:
String[] s = "1.31".split("\.");
System.out.println(s[s.length - 1].length());
Using BigDecimal might have the advantage that it checks if the string is actually a number; using the string method you have to do it yourself. Also, if you have the numbers as double you can't differentiate between 1.31
and 1.310
(they're exactly the same double) like others have pointed out as well.
add a comment
|
You could use BigDecimal.scale() if you pass the number as a String like this:
BigDecimal a = new BigDecimal("1.31");
System.out.println(a.scale()); //prints 2
BigDecimal b = new BigDecimal("1.310");
System.out.println(b.scale()); //prints 3
but if you already have the number as string you might as well just parse the string with a regex to see how many digits there are:
String[] s = "1.31".split("\.");
System.out.println(s[s.length - 1].length());
Using BigDecimal might have the advantage that it checks if the string is actually a number; using the string method you have to do it yourself. Also, if you have the numbers as double you can't differentiate between 1.31
and 1.310
(they're exactly the same double) like others have pointed out as well.
You could use BigDecimal.scale() if you pass the number as a String like this:
BigDecimal a = new BigDecimal("1.31");
System.out.println(a.scale()); //prints 2
BigDecimal b = new BigDecimal("1.310");
System.out.println(b.scale()); //prints 3
but if you already have the number as string you might as well just parse the string with a regex to see how many digits there are:
String[] s = "1.31".split("\.");
System.out.println(s[s.length - 1].length());
Using BigDecimal might have the advantage that it checks if the string is actually a number; using the string method you have to do it yourself. Also, if you have the numbers as double you can't differentiate between 1.31
and 1.310
(they're exactly the same double) like others have pointed out as well.
answered Jul 26 '10 at 11:07
Andrei FierbinteanuAndrei Fierbinteanu
6,1083 gold badges25 silver badges43 bronze badges
6,1083 gold badges25 silver badges43 bronze badges
add a comment
|
add a comment
|
The number of decimal places in a double is 16.
64-bit numbers. 52-bit Mantissa. 52 bits is about 16 decimal digits.
See http://java.sun.com/docs/books/jls/second_edition/html/typesValues.doc.html.
double, whose values include the 64-bit IEEE 754 floating-point numbers.
See http://en.wikipedia.org/wiki/IEEE_754-2008
2
No, that's the number of decimal digits, and it's wrong, it is 15.9. Consider "123456789012345". Fifteen decimal digits, zero decimal places. "12345678901234.5". Fifteen decimal digits, one decimal place. Etc.
– user207421
Jul 27 '10 at 4:08
3
@EJP: I would think that 15.9 is "About 16". It appears from your comment that you don't think 15.9 is "about 16". If you want to claim 15.9 is not "about 16", then you're wrong also, since it's not 15.9, either. Wikipedia says "17 decimal digits" and 15.955 digits.
– S.Lott
Jul 27 '10 at 9:59
4
@EJP: Please read the IEEE standard carefully. In particular, read about the implicit bits in the significand.
– S.Lott
Jul 27 '10 at 11:31
3
OK, we are just quibbling here, but it is 15.9545897701910000. To 16 decimal places ;-)
– user207421
Jul 28 '10 at 2:58
2
OK. I am quibbling.
– user207421
Jul 28 '10 at 10:50
|
show 4 more comments
The number of decimal places in a double is 16.
64-bit numbers. 52-bit Mantissa. 52 bits is about 16 decimal digits.
See http://java.sun.com/docs/books/jls/second_edition/html/typesValues.doc.html.
double, whose values include the 64-bit IEEE 754 floating-point numbers.
See http://en.wikipedia.org/wiki/IEEE_754-2008
2
No, that's the number of decimal digits, and it's wrong, it is 15.9. Consider "123456789012345". Fifteen decimal digits, zero decimal places. "12345678901234.5". Fifteen decimal digits, one decimal place. Etc.
– user207421
Jul 27 '10 at 4:08
3
@EJP: I would think that 15.9 is "About 16". It appears from your comment that you don't think 15.9 is "about 16". If you want to claim 15.9 is not "about 16", then you're wrong also, since it's not 15.9, either. Wikipedia says "17 decimal digits" and 15.955 digits.
– S.Lott
Jul 27 '10 at 9:59
4
@EJP: Please read the IEEE standard carefully. In particular, read about the implicit bits in the significand.
– S.Lott
Jul 27 '10 at 11:31
3
OK, we are just quibbling here, but it is 15.9545897701910000. To 16 decimal places ;-)
– user207421
Jul 28 '10 at 2:58
2
OK. I am quibbling.
– user207421
Jul 28 '10 at 10:50
|
show 4 more comments
The number of decimal places in a double is 16.
64-bit numbers. 52-bit Mantissa. 52 bits is about 16 decimal digits.
See http://java.sun.com/docs/books/jls/second_edition/html/typesValues.doc.html.
double, whose values include the 64-bit IEEE 754 floating-point numbers.
See http://en.wikipedia.org/wiki/IEEE_754-2008
The number of decimal places in a double is 16.
64-bit numbers. 52-bit Mantissa. 52 bits is about 16 decimal digits.
See http://java.sun.com/docs/books/jls/second_edition/html/typesValues.doc.html.
double, whose values include the 64-bit IEEE 754 floating-point numbers.
See http://en.wikipedia.org/wiki/IEEE_754-2008
answered Jul 26 '10 at 11:00
S.LottS.Lott
329k71 gold badges455 silver badges732 bronze badges
329k71 gold badges455 silver badges732 bronze badges
2
No, that's the number of decimal digits, and it's wrong, it is 15.9. Consider "123456789012345". Fifteen decimal digits, zero decimal places. "12345678901234.5". Fifteen decimal digits, one decimal place. Etc.
– user207421
Jul 27 '10 at 4:08
3
@EJP: I would think that 15.9 is "About 16". It appears from your comment that you don't think 15.9 is "about 16". If you want to claim 15.9 is not "about 16", then you're wrong also, since it's not 15.9, either. Wikipedia says "17 decimal digits" and 15.955 digits.
– S.Lott
Jul 27 '10 at 9:59
4
@EJP: Please read the IEEE standard carefully. In particular, read about the implicit bits in the significand.
– S.Lott
Jul 27 '10 at 11:31
3
OK, we are just quibbling here, but it is 15.9545897701910000. To 16 decimal places ;-)
– user207421
Jul 28 '10 at 2:58
2
OK. I am quibbling.
– user207421
Jul 28 '10 at 10:50
|
show 4 more comments
2
No, that's the number of decimal digits, and it's wrong, it is 15.9. Consider "123456789012345". Fifteen decimal digits, zero decimal places. "12345678901234.5". Fifteen decimal digits, one decimal place. Etc.
– user207421
Jul 27 '10 at 4:08
3
@EJP: I would think that 15.9 is "About 16". It appears from your comment that you don't think 15.9 is "about 16". If you want to claim 15.9 is not "about 16", then you're wrong also, since it's not 15.9, either. Wikipedia says "17 decimal digits" and 15.955 digits.
– S.Lott
Jul 27 '10 at 9:59
4
@EJP: Please read the IEEE standard carefully. In particular, read about the implicit bits in the significand.
– S.Lott
Jul 27 '10 at 11:31
3
OK, we are just quibbling here, but it is 15.9545897701910000. To 16 decimal places ;-)
– user207421
Jul 28 '10 at 2:58
2
OK. I am quibbling.
– user207421
Jul 28 '10 at 10:50
2
2
No, that's the number of decimal digits, and it's wrong, it is 15.9. Consider "123456789012345". Fifteen decimal digits, zero decimal places. "12345678901234.5". Fifteen decimal digits, one decimal place. Etc.
– user207421
Jul 27 '10 at 4:08
No, that's the number of decimal digits, and it's wrong, it is 15.9. Consider "123456789012345". Fifteen decimal digits, zero decimal places. "12345678901234.5". Fifteen decimal digits, one decimal place. Etc.
– user207421
Jul 27 '10 at 4:08
3
3
@EJP: I would think that 15.9 is "About 16". It appears from your comment that you don't think 15.9 is "about 16". If you want to claim 15.9 is not "about 16", then you're wrong also, since it's not 15.9, either. Wikipedia says "17 decimal digits" and 15.955 digits.
– S.Lott
Jul 27 '10 at 9:59
@EJP: I would think that 15.9 is "About 16". It appears from your comment that you don't think 15.9 is "about 16". If you want to claim 15.9 is not "about 16", then you're wrong also, since it's not 15.9, either. Wikipedia says "17 decimal digits" and 15.955 digits.
– S.Lott
Jul 27 '10 at 9:59
4
4
@EJP: Please read the IEEE standard carefully. In particular, read about the implicit bits in the significand.
– S.Lott
Jul 27 '10 at 11:31
@EJP: Please read the IEEE standard carefully. In particular, read about the implicit bits in the significand.
– S.Lott
Jul 27 '10 at 11:31
3
3
OK, we are just quibbling here, but it is 15.9545897701910000. To 16 decimal places ;-)
– user207421
Jul 28 '10 at 2:58
OK, we are just quibbling here, but it is 15.9545897701910000. To 16 decimal places ;-)
– user207421
Jul 28 '10 at 2:58
2
2
OK. I am quibbling.
– user207421
Jul 28 '10 at 10:50
OK. I am quibbling.
– user207421
Jul 28 '10 at 10:50
|
show 4 more comments
No, there is no built-in function that I know about.
There is a simple way to do this, though. Double.toString will give you a string containing ALL significant decimal digits in the double. The following are some properties of that string:
- The String that results may be in decimal notation or scientific
notation, depending on the value of the double. - Doubles that convert to decimals 10,000,000 or larger or smaller than
1/1000 result in scientific notation. Otherwise, they are in decimal
notation.
Using Double.toString to figure out how many decimal places there are essentially comprises how many significant digits to the right of the decimal point minus a scientific notation exponent, if there is one. Decimal notation will always have at least one digit to the right of the decimal point, and at least one digit to the left of the decimal point, even if it is a zero. Since we are concerned about decimal places for significant digits, a trailing zero to the right of the decimal point is a concern and should not be counted as a decimal place.
The following code will make a good calculation for you:
StringBuffer stringBuffer = new StringBuffer(Double.toString(1234.567890D));
System.out.println(stringBuffer.toString());
int i; // general purpose character index
int exponent;
int decimalPlaces;
if ((i = stringBuffer.indexOf("E")) > -1) // scientific notation...
// turn scientific notation exponent into an integer
exponent = Integer.parseInt(stringBuffer.substring(i + 1));
// truncate the exponent from the StringBuffer
stringBuffer = stringBuffer.delete(i, stringBuffer.length());
else // decimal notation, could be trailing zero
exponent = 0; // no exponent, so zero
// point i to trailing zero and truncate it, if there is one
if (stringBuffer.charAt((i = stringBuffer.length() - 1)) == '0')
stringBuffer = stringBuffer.deleteCharAt(i); // delete trailing zero
// stringBuffer now contains only significant digits to the
// right of the decimal point, if there are any
decimalPlaces = stringBuffer.length() - 1 - stringBuffer.indexOf(".") - exponent;
// zero or positive number is decimal places
// negative number is number of zeroes to the left of the decimal point
// between the decimal point and the least significant digit
System.out.println(decimalPlaces);
I have some questions about the question posed. What kind of precision is expected with the decimal representation of a double? Are doubles being used to inappropriately perform decimal computations? Decimal computations with decimal fractions using floats and doubles can have results that unexpectedly have 16 or 17 significant digits and may be only approximations of the expected results from equivalent decimal computations.
One aspect of float, doubles, long doubles (aka quads) that seems to stymie programmers and designers is that all these formats are actually stored as binary fractional numbers that can only approximate decimal numbers except for a very, very few numbers, most of which are fairly close to the values 1, -1, plus the value zero. As one progresses towards positive infinity or zero from 1, or towards negative infinity or zero from -1, the sparseness of the approximation will become apparent.
Almost all decimal fractions have no direct representation in floats and doubles. Only decimal fractions that can be comprised from the sum of some combination of the following series of fractions have an exact representation:
1, 1/2, 1/4, 1/8, 1/16, 1/32, 1/64, 1/128, 1/256, ..., 1/4503599627370496
All the rest are approximations.
Integers greater than +9007199254740992 or less than -9007199254740992 may not have an exact representation and the sparseness increases exponentially as integers increase above the positive or decrease below the negative values, respectively.
Another way to look at this is to realize that IEEE 64-bit doubles, normalized, approximate positive and negative decimal numbers having absolute values ranging from 2.225073858507201400 E -308 through 1.797693134862315700 E +308. However, there are only 1.8446744073709551616 E +19 values available for these approximations. That means about 1.0 E +607 decimal values share a representation with some other decimal values that are more closely approximated by a double.
The behavior of floats and doubles wrecks havoc with decimal computations requiring exact decimal accuracy, such as financial calculations and is why, unless a high-precision approximation is acceptable, one should use scaled integers and longs, or classes such as BigInteger and BigDecimal, for computations requiring exact decimal accuracy, rounding and precision.
add a comment
|
No, there is no built-in function that I know about.
There is a simple way to do this, though. Double.toString will give you a string containing ALL significant decimal digits in the double. The following are some properties of that string:
- The String that results may be in decimal notation or scientific
notation, depending on the value of the double. - Doubles that convert to decimals 10,000,000 or larger or smaller than
1/1000 result in scientific notation. Otherwise, they are in decimal
notation.
Using Double.toString to figure out how many decimal places there are essentially comprises how many significant digits to the right of the decimal point minus a scientific notation exponent, if there is one. Decimal notation will always have at least one digit to the right of the decimal point, and at least one digit to the left of the decimal point, even if it is a zero. Since we are concerned about decimal places for significant digits, a trailing zero to the right of the decimal point is a concern and should not be counted as a decimal place.
The following code will make a good calculation for you:
StringBuffer stringBuffer = new StringBuffer(Double.toString(1234.567890D));
System.out.println(stringBuffer.toString());
int i; // general purpose character index
int exponent;
int decimalPlaces;
if ((i = stringBuffer.indexOf("E")) > -1) // scientific notation...
// turn scientific notation exponent into an integer
exponent = Integer.parseInt(stringBuffer.substring(i + 1));
// truncate the exponent from the StringBuffer
stringBuffer = stringBuffer.delete(i, stringBuffer.length());
else // decimal notation, could be trailing zero
exponent = 0; // no exponent, so zero
// point i to trailing zero and truncate it, if there is one
if (stringBuffer.charAt((i = stringBuffer.length() - 1)) == '0')
stringBuffer = stringBuffer.deleteCharAt(i); // delete trailing zero
// stringBuffer now contains only significant digits to the
// right of the decimal point, if there are any
decimalPlaces = stringBuffer.length() - 1 - stringBuffer.indexOf(".") - exponent;
// zero or positive number is decimal places
// negative number is number of zeroes to the left of the decimal point
// between the decimal point and the least significant digit
System.out.println(decimalPlaces);
I have some questions about the question posed. What kind of precision is expected with the decimal representation of a double? Are doubles being used to inappropriately perform decimal computations? Decimal computations with decimal fractions using floats and doubles can have results that unexpectedly have 16 or 17 significant digits and may be only approximations of the expected results from equivalent decimal computations.
One aspect of float, doubles, long doubles (aka quads) that seems to stymie programmers and designers is that all these formats are actually stored as binary fractional numbers that can only approximate decimal numbers except for a very, very few numbers, most of which are fairly close to the values 1, -1, plus the value zero. As one progresses towards positive infinity or zero from 1, or towards negative infinity or zero from -1, the sparseness of the approximation will become apparent.
Almost all decimal fractions have no direct representation in floats and doubles. Only decimal fractions that can be comprised from the sum of some combination of the following series of fractions have an exact representation:
1, 1/2, 1/4, 1/8, 1/16, 1/32, 1/64, 1/128, 1/256, ..., 1/4503599627370496
All the rest are approximations.
Integers greater than +9007199254740992 or less than -9007199254740992 may not have an exact representation and the sparseness increases exponentially as integers increase above the positive or decrease below the negative values, respectively.
Another way to look at this is to realize that IEEE 64-bit doubles, normalized, approximate positive and negative decimal numbers having absolute values ranging from 2.225073858507201400 E -308 through 1.797693134862315700 E +308. However, there are only 1.8446744073709551616 E +19 values available for these approximations. That means about 1.0 E +607 decimal values share a representation with some other decimal values that are more closely approximated by a double.
The behavior of floats and doubles wrecks havoc with decimal computations requiring exact decimal accuracy, such as financial calculations and is why, unless a high-precision approximation is acceptable, one should use scaled integers and longs, or classes such as BigInteger and BigDecimal, for computations requiring exact decimal accuracy, rounding and precision.
add a comment
|
No, there is no built-in function that I know about.
There is a simple way to do this, though. Double.toString will give you a string containing ALL significant decimal digits in the double. The following are some properties of that string:
- The String that results may be in decimal notation or scientific
notation, depending on the value of the double. - Doubles that convert to decimals 10,000,000 or larger or smaller than
1/1000 result in scientific notation. Otherwise, they are in decimal
notation.
Using Double.toString to figure out how many decimal places there are essentially comprises how many significant digits to the right of the decimal point minus a scientific notation exponent, if there is one. Decimal notation will always have at least one digit to the right of the decimal point, and at least one digit to the left of the decimal point, even if it is a zero. Since we are concerned about decimal places for significant digits, a trailing zero to the right of the decimal point is a concern and should not be counted as a decimal place.
The following code will make a good calculation for you:
StringBuffer stringBuffer = new StringBuffer(Double.toString(1234.567890D));
System.out.println(stringBuffer.toString());
int i; // general purpose character index
int exponent;
int decimalPlaces;
if ((i = stringBuffer.indexOf("E")) > -1) // scientific notation...
// turn scientific notation exponent into an integer
exponent = Integer.parseInt(stringBuffer.substring(i + 1));
// truncate the exponent from the StringBuffer
stringBuffer = stringBuffer.delete(i, stringBuffer.length());
else // decimal notation, could be trailing zero
exponent = 0; // no exponent, so zero
// point i to trailing zero and truncate it, if there is one
if (stringBuffer.charAt((i = stringBuffer.length() - 1)) == '0')
stringBuffer = stringBuffer.deleteCharAt(i); // delete trailing zero
// stringBuffer now contains only significant digits to the
// right of the decimal point, if there are any
decimalPlaces = stringBuffer.length() - 1 - stringBuffer.indexOf(".") - exponent;
// zero or positive number is decimal places
// negative number is number of zeroes to the left of the decimal point
// between the decimal point and the least significant digit
System.out.println(decimalPlaces);
I have some questions about the question posed. What kind of precision is expected with the decimal representation of a double? Are doubles being used to inappropriately perform decimal computations? Decimal computations with decimal fractions using floats and doubles can have results that unexpectedly have 16 or 17 significant digits and may be only approximations of the expected results from equivalent decimal computations.
One aspect of float, doubles, long doubles (aka quads) that seems to stymie programmers and designers is that all these formats are actually stored as binary fractional numbers that can only approximate decimal numbers except for a very, very few numbers, most of which are fairly close to the values 1, -1, plus the value zero. As one progresses towards positive infinity or zero from 1, or towards negative infinity or zero from -1, the sparseness of the approximation will become apparent.
Almost all decimal fractions have no direct representation in floats and doubles. Only decimal fractions that can be comprised from the sum of some combination of the following series of fractions have an exact representation:
1, 1/2, 1/4, 1/8, 1/16, 1/32, 1/64, 1/128, 1/256, ..., 1/4503599627370496
All the rest are approximations.
Integers greater than +9007199254740992 or less than -9007199254740992 may not have an exact representation and the sparseness increases exponentially as integers increase above the positive or decrease below the negative values, respectively.
Another way to look at this is to realize that IEEE 64-bit doubles, normalized, approximate positive and negative decimal numbers having absolute values ranging from 2.225073858507201400 E -308 through 1.797693134862315700 E +308. However, there are only 1.8446744073709551616 E +19 values available for these approximations. That means about 1.0 E +607 decimal values share a representation with some other decimal values that are more closely approximated by a double.
The behavior of floats and doubles wrecks havoc with decimal computations requiring exact decimal accuracy, such as financial calculations and is why, unless a high-precision approximation is acceptable, one should use scaled integers and longs, or classes such as BigInteger and BigDecimal, for computations requiring exact decimal accuracy, rounding and precision.
No, there is no built-in function that I know about.
There is a simple way to do this, though. Double.toString will give you a string containing ALL significant decimal digits in the double. The following are some properties of that string:
- The String that results may be in decimal notation or scientific
notation, depending on the value of the double. - Doubles that convert to decimals 10,000,000 or larger or smaller than
1/1000 result in scientific notation. Otherwise, they are in decimal
notation.
Using Double.toString to figure out how many decimal places there are essentially comprises how many significant digits to the right of the decimal point minus a scientific notation exponent, if there is one. Decimal notation will always have at least one digit to the right of the decimal point, and at least one digit to the left of the decimal point, even if it is a zero. Since we are concerned about decimal places for significant digits, a trailing zero to the right of the decimal point is a concern and should not be counted as a decimal place.
The following code will make a good calculation for you:
StringBuffer stringBuffer = new StringBuffer(Double.toString(1234.567890D));
System.out.println(stringBuffer.toString());
int i; // general purpose character index
int exponent;
int decimalPlaces;
if ((i = stringBuffer.indexOf("E")) > -1) // scientific notation...
// turn scientific notation exponent into an integer
exponent = Integer.parseInt(stringBuffer.substring(i + 1));
// truncate the exponent from the StringBuffer
stringBuffer = stringBuffer.delete(i, stringBuffer.length());
else // decimal notation, could be trailing zero
exponent = 0; // no exponent, so zero
// point i to trailing zero and truncate it, if there is one
if (stringBuffer.charAt((i = stringBuffer.length() - 1)) == '0')
stringBuffer = stringBuffer.deleteCharAt(i); // delete trailing zero
// stringBuffer now contains only significant digits to the
// right of the decimal point, if there are any
decimalPlaces = stringBuffer.length() - 1 - stringBuffer.indexOf(".") - exponent;
// zero or positive number is decimal places
// negative number is number of zeroes to the left of the decimal point
// between the decimal point and the least significant digit
System.out.println(decimalPlaces);
I have some questions about the question posed. What kind of precision is expected with the decimal representation of a double? Are doubles being used to inappropriately perform decimal computations? Decimal computations with decimal fractions using floats and doubles can have results that unexpectedly have 16 or 17 significant digits and may be only approximations of the expected results from equivalent decimal computations.
One aspect of float, doubles, long doubles (aka quads) that seems to stymie programmers and designers is that all these formats are actually stored as binary fractional numbers that can only approximate decimal numbers except for a very, very few numbers, most of which are fairly close to the values 1, -1, plus the value zero. As one progresses towards positive infinity or zero from 1, or towards negative infinity or zero from -1, the sparseness of the approximation will become apparent.
Almost all decimal fractions have no direct representation in floats and doubles. Only decimal fractions that can be comprised from the sum of some combination of the following series of fractions have an exact representation:
1, 1/2, 1/4, 1/8, 1/16, 1/32, 1/64, 1/128, 1/256, ..., 1/4503599627370496
All the rest are approximations.
Integers greater than +9007199254740992 or less than -9007199254740992 may not have an exact representation and the sparseness increases exponentially as integers increase above the positive or decrease below the negative values, respectively.
Another way to look at this is to realize that IEEE 64-bit doubles, normalized, approximate positive and negative decimal numbers having absolute values ranging from 2.225073858507201400 E -308 through 1.797693134862315700 E +308. However, there are only 1.8446744073709551616 E +19 values available for these approximations. That means about 1.0 E +607 decimal values share a representation with some other decimal values that are more closely approximated by a double.
The behavior of floats and doubles wrecks havoc with decimal computations requiring exact decimal accuracy, such as financial calculations and is why, unless a high-precision approximation is acceptable, one should use scaled integers and longs, or classes such as BigInteger and BigDecimal, for computations requiring exact decimal accuracy, rounding and precision.
answered Jul 11 '12 at 2:10
JimJim
2,4621 gold badge17 silver badges14 bronze badges
2,4621 gold badge17 silver badges14 bronze badges
add a comment
|
add a comment
|
// ****************************************************************
public int getDecimals(double doubleValue)
// ****************************************************************
BigDecimal bd1 = new BigDecimal(Double.toString(doubleValue)).stripTrailingZeros();
return bd1.scale();
The toString part is crucial.
– David I.
May 6 '14 at 15:39
add a comment
|
// ****************************************************************
public int getDecimals(double doubleValue)
// ****************************************************************
BigDecimal bd1 = new BigDecimal(Double.toString(doubleValue)).stripTrailingZeros();
return bd1.scale();
The toString part is crucial.
– David I.
May 6 '14 at 15:39
add a comment
|
// ****************************************************************
public int getDecimals(double doubleValue)
// ****************************************************************
BigDecimal bd1 = new BigDecimal(Double.toString(doubleValue)).stripTrailingZeros();
return bd1.scale();
// ****************************************************************
public int getDecimals(double doubleValue)
// ****************************************************************
BigDecimal bd1 = new BigDecimal(Double.toString(doubleValue)).stripTrailingZeros();
return bd1.scale();
edited Nov 28 '12 at 14:22
answered Nov 28 '12 at 13:10
Erik WErik W
212 bronze badges
212 bronze badges
The toString part is crucial.
– David I.
May 6 '14 at 15:39
add a comment
|
The toString part is crucial.
– David I.
May 6 '14 at 15:39
The toString part is crucial.
– David I.
May 6 '14 at 15:39
The toString part is crucial.
– David I.
May 6 '14 at 15:39
add a comment
|
From many long years ago, I recall an answer of 16 digits, total of before and after the decimal point.
I wrote a tiny bit of code to test that.
public class test
public static void main(String[] args)
double x;`enter code here`
x = 3411.999999999999;
System.out.println("16: "+x); // gives 3411.999999999999
x = 3411.9999999999999;
System.out.println("17: "+x); // gives 3412.0
x = 0.9999999999999999;
System.out.println("16: "+x); // gives 0.9999999999999999
x = 0.99999999999999999;
System.out.println("17: "+x); // gives 1.0
There 4+12 = 16 digits. A run outputs 3411.999999999999.
Now add one more 9 behind the decimal point for a total of 17 - 3411.9999999999999 - and rerun. The value printed is 3412.0. In this case, we overload the internal representation of x, and the number is rounded internally to store.
The println faithfully prints what it sees internally. There are only so many bits - 64 to be exact - to hold the double floating number (significand and exponent - see IEEE 754 for the gory details).
Play around with the value of x and you'll see the effects. For instance, 0.9999999999999999 (16 9s)give output 0.9999999999999999; 0.99999999999999999 (17 9s) gives 1.0.
Hope this helps.
add a comment
|
From many long years ago, I recall an answer of 16 digits, total of before and after the decimal point.
I wrote a tiny bit of code to test that.
public class test
public static void main(String[] args)
double x;`enter code here`
x = 3411.999999999999;
System.out.println("16: "+x); // gives 3411.999999999999
x = 3411.9999999999999;
System.out.println("17: "+x); // gives 3412.0
x = 0.9999999999999999;
System.out.println("16: "+x); // gives 0.9999999999999999
x = 0.99999999999999999;
System.out.println("17: "+x); // gives 1.0
There 4+12 = 16 digits. A run outputs 3411.999999999999.
Now add one more 9 behind the decimal point for a total of 17 - 3411.9999999999999 - and rerun. The value printed is 3412.0. In this case, we overload the internal representation of x, and the number is rounded internally to store.
The println faithfully prints what it sees internally. There are only so many bits - 64 to be exact - to hold the double floating number (significand and exponent - see IEEE 754 for the gory details).
Play around with the value of x and you'll see the effects. For instance, 0.9999999999999999 (16 9s)give output 0.9999999999999999; 0.99999999999999999 (17 9s) gives 1.0.
Hope this helps.
add a comment
|
From many long years ago, I recall an answer of 16 digits, total of before and after the decimal point.
I wrote a tiny bit of code to test that.
public class test
public static void main(String[] args)
double x;`enter code here`
x = 3411.999999999999;
System.out.println("16: "+x); // gives 3411.999999999999
x = 3411.9999999999999;
System.out.println("17: "+x); // gives 3412.0
x = 0.9999999999999999;
System.out.println("16: "+x); // gives 0.9999999999999999
x = 0.99999999999999999;
System.out.println("17: "+x); // gives 1.0
There 4+12 = 16 digits. A run outputs 3411.999999999999.
Now add one more 9 behind the decimal point for a total of 17 - 3411.9999999999999 - and rerun. The value printed is 3412.0. In this case, we overload the internal representation of x, and the number is rounded internally to store.
The println faithfully prints what it sees internally. There are only so many bits - 64 to be exact - to hold the double floating number (significand and exponent - see IEEE 754 for the gory details).
Play around with the value of x and you'll see the effects. For instance, 0.9999999999999999 (16 9s)give output 0.9999999999999999; 0.99999999999999999 (17 9s) gives 1.0.
Hope this helps.
From many long years ago, I recall an answer of 16 digits, total of before and after the decimal point.
I wrote a tiny bit of code to test that.
public class test
public static void main(String[] args)
double x;`enter code here`
x = 3411.999999999999;
System.out.println("16: "+x); // gives 3411.999999999999
x = 3411.9999999999999;
System.out.println("17: "+x); // gives 3412.0
x = 0.9999999999999999;
System.out.println("16: "+x); // gives 0.9999999999999999
x = 0.99999999999999999;
System.out.println("17: "+x); // gives 1.0
There 4+12 = 16 digits. A run outputs 3411.999999999999.
Now add one more 9 behind the decimal point for a total of 17 - 3411.9999999999999 - and rerun. The value printed is 3412.0. In this case, we overload the internal representation of x, and the number is rounded internally to store.
The println faithfully prints what it sees internally. There are only so many bits - 64 to be exact - to hold the double floating number (significand and exponent - see IEEE 754 for the gory details).
Play around with the value of x and you'll see the effects. For instance, 0.9999999999999999 (16 9s)give output 0.9999999999999999; 0.99999999999999999 (17 9s) gives 1.0.
Hope this helps.
edited Jun 3 '13 at 17:57
Daniel
7,69918 gold badges72 silver badges105 bronze badges
7,69918 gold badges72 silver badges105 bronze badges
answered Jun 3 '13 at 17:37
user2448902user2448902
1
1
add a comment
|
add a comment
|
StringBuffer stringBuffer = new StringBuffer(Double.toString(ratioGrossYield));
int i; // general purpose character index
int exponent;
int decimalPlaces;
if ((i = stringBuffer.indexOf("E")) > -1) // scientific notation...
// turn scientific notation exponent into an integer
exponent = Integer.parseInt(stringBuffer.substring(i + 1));
// truncate the exponent from the StringBuffer
stringBuffer = stringBuffer.delete(i, stringBuffer.length());
else // decimal notation, could be trailing zero
exponent = 0; // no exponent, so zero
// point i to trailing zero and truncate it, if there is one
if (stringBuffer.charAt((i = stringBuffer.length() - 1)) == '0')
stringBuffer = stringBuffer.deleteCharAt(i); // delete trailing zero
// stringBuffer now contains only significant digits to the
// right of the decimal point, if there are any
decimalPlaces = stringBuffer.length() - 1 - stringBuffer.indexOf(".") - exponent;
// zero or positive number is decimal places
// negative number is number of zeroes to the left of the decimal point
// between the decimal point and the least significant digit
if (stringBuffer.charAt(stringBuffer.length() - 1) == '0')
return decimalPlaces-1;
else
return decimalPlaces;
add a comment
|
StringBuffer stringBuffer = new StringBuffer(Double.toString(ratioGrossYield));
int i; // general purpose character index
int exponent;
int decimalPlaces;
if ((i = stringBuffer.indexOf("E")) > -1) // scientific notation...
// turn scientific notation exponent into an integer
exponent = Integer.parseInt(stringBuffer.substring(i + 1));
// truncate the exponent from the StringBuffer
stringBuffer = stringBuffer.delete(i, stringBuffer.length());
else // decimal notation, could be trailing zero
exponent = 0; // no exponent, so zero
// point i to trailing zero and truncate it, if there is one
if (stringBuffer.charAt((i = stringBuffer.length() - 1)) == '0')
stringBuffer = stringBuffer.deleteCharAt(i); // delete trailing zero
// stringBuffer now contains only significant digits to the
// right of the decimal point, if there are any
decimalPlaces = stringBuffer.length() - 1 - stringBuffer.indexOf(".") - exponent;
// zero or positive number is decimal places
// negative number is number of zeroes to the left of the decimal point
// between the decimal point and the least significant digit
if (stringBuffer.charAt(stringBuffer.length() - 1) == '0')
return decimalPlaces-1;
else
return decimalPlaces;
add a comment
|
StringBuffer stringBuffer = new StringBuffer(Double.toString(ratioGrossYield));
int i; // general purpose character index
int exponent;
int decimalPlaces;
if ((i = stringBuffer.indexOf("E")) > -1) // scientific notation...
// turn scientific notation exponent into an integer
exponent = Integer.parseInt(stringBuffer.substring(i + 1));
// truncate the exponent from the StringBuffer
stringBuffer = stringBuffer.delete(i, stringBuffer.length());
else // decimal notation, could be trailing zero
exponent = 0; // no exponent, so zero
// point i to trailing zero and truncate it, if there is one
if (stringBuffer.charAt((i = stringBuffer.length() - 1)) == '0')
stringBuffer = stringBuffer.deleteCharAt(i); // delete trailing zero
// stringBuffer now contains only significant digits to the
// right of the decimal point, if there are any
decimalPlaces = stringBuffer.length() - 1 - stringBuffer.indexOf(".") - exponent;
// zero or positive number is decimal places
// negative number is number of zeroes to the left of the decimal point
// between the decimal point and the least significant digit
if (stringBuffer.charAt(stringBuffer.length() - 1) == '0')
return decimalPlaces-1;
else
return decimalPlaces;
StringBuffer stringBuffer = new StringBuffer(Double.toString(ratioGrossYield));
int i; // general purpose character index
int exponent;
int decimalPlaces;
if ((i = stringBuffer.indexOf("E")) > -1) // scientific notation...
// turn scientific notation exponent into an integer
exponent = Integer.parseInt(stringBuffer.substring(i + 1));
// truncate the exponent from the StringBuffer
stringBuffer = stringBuffer.delete(i, stringBuffer.length());
else // decimal notation, could be trailing zero
exponent = 0; // no exponent, so zero
// point i to trailing zero and truncate it, if there is one
if (stringBuffer.charAt((i = stringBuffer.length() - 1)) == '0')
stringBuffer = stringBuffer.deleteCharAt(i); // delete trailing zero
// stringBuffer now contains only significant digits to the
// right of the decimal point, if there are any
decimalPlaces = stringBuffer.length() - 1 - stringBuffer.indexOf(".") - exponent;
// zero or positive number is decimal places
// negative number is number of zeroes to the left of the decimal point
// between the decimal point and the least significant digit
if (stringBuffer.charAt(stringBuffer.length() - 1) == '0')
return decimalPlaces-1;
else
return decimalPlaces;
edited Apr 23 '13 at 7:03
Helen
39.3k5 gold badges96 silver badges150 bronze badges
39.3k5 gold badges96 silver badges150 bronze badges
answered Apr 23 '13 at 6:52
SushilSushil
1
1
add a comment
|
add a comment
|
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f3334168%2fhow-many-decimal-places-in-a-double-java%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown