How to convert String to Double without using parseDouble?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • deBiidpOL
    New Member
    • Sep 2013
    • 1

    #1

    How to convert String to Double without using parseDouble?

    Manually converting a string to double..
  • Nepomuk
    Recognized Expert Specialist
    • Aug 2007
    • 3111

    #2
    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".charA t(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. :-)

    Comment

    Working...