Java How to represent a decimal number in a long
Java How to represent a decimal number in a long
How do I convert a String number: "6542.5699999999997" into a long? Lets say I want to have 8 digit precision in the long so it should look like:
long: 654257000000
And no I don't want to use a BigInt.
Round it then multiply it up. Cast it to a long to truncate the decimals
– Boris the Spider
Sep 16 '18 at 6:58
2 Answers
2
You can first multiply, then round like so:
long val = (long)(6542.5699999999997 * 100000000 + 0.5);
If the number can also be negative, you have to handle that case separately because the + 0.5
trick works only for positive values.
+ 0.5
If the input is 6.569 the result must be 657000000 but the output of this code is 656900000
– Rahim Dastar
Sep 16 '18 at 7:48
@RahimDastar I don't get it, why do you want a result of 657000000.
– Henry
Sep 16 '18 at 7:54
@RahimDastar well, the OP said 8 digits precision. So the rounding should be at the 8th decimal.
– Henry
Sep 16 '18 at 7:58
Note: for negative numbers you need to
- 0.5
;) +1– Peter Lawrey
Sep 16 '18 at 9:07
- 0.5
BTW To convert back you need to
/ 1e8
not * 1e-8
– Peter Lawrey
Sep 16 '18 at 9:08
/ 1e8
* 1e-8
Try this:
NumberFormat formatter = new DecimalFormat("#0.00000000");
String longStr = formatter.format(6542.5699999999997).replaceAll("\D", "");
Long longVal = Long.parseLong(longStr);
import
java.text.NumberFormat
and java.text.DecimalFormat
– pkpnd
Sep 16 '18 at 7:23
java.text.NumberFormat
java.text.DecimalFormat
This is hugely slow and inefficient. Using mathematical operations will be rather more performant.
– Boris the Spider
Sep 16 '18 at 7:36
That created quite a few objects, when actually you don't need to create any.
– Peter Lawrey
Sep 16 '18 at 9:07
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy
How exact does the precision have to be? Is it always 8 digits after the decimal point, regardless of how many digits are before the decimal point? If so, then you'll probably have to parse the string yourself, since none of the primitive types can handle arbitrary precision.
– pkpnd
Sep 16 '18 at 6:49