By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,800 Members | 1,404 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,800 IT Pros & Developers. It's quick & easy.

How to convert String to Double without using parseDouble?

P: 1
Manually converting a string to double..
Sep 8 '13 #1
Share this Question
Share on Google+
1 Reply


Nepomuk
Expert 2.5K+
P: 3,112
Hi deBiidpOL and welcome to bytes.com!

The String class has several useful functions, the best for this problem is probably charAt(int). This will return the character represented at a certain position in the string, so for example [code=java]"123.456".charAt(1)[/url] would be a '2' (as it starts counting with 0).

As soon as you have a character, you'll have to somehow convert it into part of the Double. You have 3 different situations I can think of that might occur:
  1. A sign, namely '-' or, possibly, '+'. This will decide whether the Double is positive or negative.
  2. A digit. If your character represents a digit you can handle that.
  3. A decimal point. If you find one of these, all characters right of this should be added to the Double accordingly.
Now, one point to consider how computers handle floating point numbers. This article is a classic and should be helpful to you. Basically what you have to take from it is that there may be rounding errors when converting a String to a Double, so I would recommend using a different number type until just before you need the Double. For example, you could have an Integer which you then convert to a Double at the end. Of course, the decimal point position would have to be saved to make sure you can have digits after the decimal point.

Short of solving it for you, that's all I can think of right now. Hope it helps. :-)
Sep 8 '13 #2

Post your reply

Sign in to post your reply or Sign up for a free account.