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.






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






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

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Crossroads (UK TV series)

ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế