Re: Desperately seeking strtod()
- From: Eric Sosman <eric.sosman@xxxxxxx>
- Date: Wed, 27 Jul 2005 17:20:32 -0400
.. wrote:
> On Wed, 27 Jul 2005, Eric Sosman wrote:
>
>
>> This is probably simple, but I must be looking in
>>the wrong places ... I'm trying to do what the strtod()
>>function does for me in C: Find the longest prefix of a
>>string that looks like a number, produce its numeric
>>value, and tell me where the unconverted suffix starts.
>>
>> This sounds like a job for DecimalFormat.parse(), but
>>I can't get it to accept all the things I'd like it to
>>consider as numbers. Constructed from the pattern "0E0"
>>or "#E0" (or "0e0" or "#e0"), a DecimalFormat will happily
>>parse "1" and "1.2" and ".2" and "-1.2E3", and "1E-3", but
>>it rejects "+1" and "1e3" and "1E+3". Some of the rejections
>>are outright failures ("+1" gives a null result, for example),
>>while others are incomplete conversions ("1E+3" produces the
>>value 1 with "E+3" as the unconverted suffix).
>>
>> Now, Double.valueOf() happily accepts and does the
>>right thing with all these forms -- but it insists on
>>converting the entire string, not just a prefix. It'd
>>be possible to do a sort of binary search to find the
>>longest prefix that doesn't provoke NumberFormatException,
>>but my stomach turns at the thought of such vileness.
>>
>> Please help an old C programmer who's trying to reform:
>>Where do I find the Java equivalent of strtod()?
>
>
> I'd imagine the string will not be very long. Assuming you don't have to
> convert a lot of numbers, use a for loop and the index method to see if
> the current character is not a number, decimal place or the letter E.
> Break out of the loop when you find the non-double character. Pass the
> substring into Double.valueOf(). Use a try/catch for the
> NumberFormatException because the simple for loop will not check for
> thing like "1E+3Everything". This will pass "1E+3E" to the valueOf method.
Thanks for the suggestion. I'm already doing something
with a similar flavor: I use a regexp to find the longest
number-ish prefix and then put it through Double.valueOf()
for a more rigorous check (the regexp matches nonsense like
"." and ".E-3").
Seems like an awful lot of work, though. DecimalFormat
sounds like the tool for the task, but so far it feels like
I'm trying to drive nails with a chain saw.
--
Eric.Sosman@xxxxxxx
.
- Follow-Ups:
- Re: Desperately seeking strtod()
- From: Ingo R. Homann
- Re: Desperately seeking strtod()
- References:
- Desperately seeking strtod()
- From: Eric Sosman
- Re: Desperately seeking strtod()
- From: "."
- Desperately seeking strtod()
- Prev by Date: need an unsigned int in java, so...
- Next by Date: Re: need an unsigned int in java, so...
- Previous by thread: Re: Desperately seeking strtod()
- Next by thread: Re: Desperately seeking strtod()
- Index(es):