Mizipzor
Mizipzor

Reputation: 52381

Java Double to String conversion without formatting

I have the number 654987. Its an ID in a database. I want to convert it to a string. The regular Double.ToString(value) makes it into scientific form, 6.54987E5. Something I dont want.

Other formatting functions Ive found checks the current locale and adds appropriate thousand separators and such. Since its an ID, I cant accept any formatting at all.

How to do it?

[Edit] To clarify: Im working on a special database that treats all numeric columns as doubles. Double is the only (numeric) type I can retrieve from the database.

Upvotes: 31

Views: 100597

Answers (9)

Yotam Abramson
Yotam Abramson

Reputation: 1

What about Long.toString((long)value) ?

Upvotes: 0

Bob
Bob

Reputation: 23010

Also you can use

double value = getValue();

NumberFormat f = NumberFormat.getInstance();
f.setGroupingUsed(false);

String strVal = f.format(value);

Upvotes: 2

Eemeli Kantola
Eemeli Kantola

Reputation: 5557

What about:

Long.toString(value)

or

new String(value)

Upvotes: 2

amit.bhayani
amit.bhayani

Reputation: 518

    double d = 56789;
    String s = d+"";

Upvotes: -3

DJClayworth
DJClayworth

Reputation: 26916

If what you are storing is an ID (i.e. something used only to identify another entity, whose actual numeric value has no significance) then you shouldn't be using Double to store it. Precision will almost certainly screw you.

If your database doesn't allow integer values then you should stored IDs as strings. If necessary make the string the string representation of the integer you want to use. With appropriate use of leading zeros you can make the alphabetic order of the string the same as the numeric order of the ints.

That should get you round the issue.

Upvotes: 1

alphazero
alphazero

Reputation: 27244

Use Long:

long id = 654987;
String str = Long.toString(id);

Upvotes: 20

Joachim Sauer
Joachim Sauer

Reputation: 308269

Use a fixed NumberFormat (specifically a DecimalFormat):

double value = getValue();
String str = new DecimalFormat("#").format(value);

alternatively simply cast to int (or long if the range of values it too big):

String str = String.valueOf((long) value);

But then again: why do you have an integer value (i.e. a "whole" number) in a double variable in the first place?

Upvotes: 33

rsp
rsp

Reputation: 23373

How about String.valueOf((long)value);

Upvotes: 6

Ned Batchelder
Ned Batchelder

Reputation: 376052

If it's an integer id in the database, use an Integer instead. Then it will format as an integer.

Upvotes: 6

Related Questions