This discussion is archived
5 Replies Latest reply: Nov 21, 2007 3:06 PM by 807603

# String valueOf(1.0E-4) is not 0.0001

Currently Being Moderated
When having the number a = 1.0E-4, I would like to represent it as:
0.0001.

How can I convert this number so that String valueOf(a) understands it as:
0.0001?

• ###### 1. Re: String valueOf(1.0E-4) is not 0.0001
Currently Being Moderated
http://java.sun.com/javase/6/docs/api/java/text/DecimalFormat.html

http://java.sun.com/javase/6/docs/api/java/lang/String.html#format(java.lang.String, java.lang.Object...)

http://java.sun.com/javase/6/docs/api/java/util/Formatter.html#syntax
• ###### 2. Re: String valueOf(1.0E-4) is not 0.0001
Currently Being Moderated
Thanks!

So, does this mean, instead of using String.valueOf(double number), I should use my own method, such as:
public String valueOf(double number)
{
DecimalFormat f = new DecimalFormat("#######.######");
String string = f.format(number);
return string;
}
?

And does my DecimalFormat say:
at most 7 digits before the decimal point and at most 6 digits after the decimal point?

Please respond, I am a beginner at this!
• ###### 3. Re: String valueOf(1.0E-4) is not 0.0001
Currently Being Moderated
BrigitAnanya wrote:
Thanks!

So, does this mean, instead of using String.valueOf(double number), I should use my own method, such as:
public String valueOf(double number)
{
DecimalFormat f = new DecimalFormat("#######.######");
String string = f.format(number);
return string;
}
?
Yes, something like that.
And does my DecimalFormat say:
at most 7 digits before the decimal point and at most 6 digits after the decimal point?
What happened when you tried it? Did it do what you wanted?
Please respond, I am a beginner at this!
• ###### 4. Re: String valueOf(1.0E-4) is not 0.0001
Currently Being Moderated
Well, I did try it, and it seemed doing what I wanted with one exception:

If the number looks like an integer, for example 10, I would like my valueOf method to return 10.0 as the String.valueOf method does. How can I accomplish this easily without having to check if my String contains a decimal point?

Thanks for looking at this!
• ###### 5. Re: String valueOf(1.0E-4) is not 0.0001
Currently Being Moderated
Ok, it's actually pretty easy to check if the string has a decimal point. So here is my full code:
public static String valueOf(double number)
{
int length, i;

DecimalFormat f = new DecimalFormat("######.#####");
String string = f.format(number);
length = string.length();
for (i = 0; i < length; i++)
{
if (string.charAt(i) == '.')
{
break;
}
}
if (i == length)
{
string = string + (".0");
}
return string;
}