Re: doubleValue (for an NSString)
Re: doubleValue (for an NSString)
- Subject: Re: doubleValue (for an NSString)
- From: John Stiles <email@hidden>
- Date: Thu, 20 Mar 2008 16:38:00 -0700
You could always do this
float value;
if (1 == sscanf([myString UTF8String], "%f", &value))
{
// the string was a valid float
}
else
{
// it wasn't
}
For integer, replace "float" with "int" and "%f" with "%d".
Localization concerns still apply in theory but in practice there are
few locales which don't use standard numeric characters. Actually, well,
I don't know if sscanf knows about using "," for the decimal separator
in Europe or not.
Quincey Morris wrote:
On Mar 20, 2008, at 16:13, Boyd Collier wrote:
According to Apple's documents, the selector doubleValue returns 0.0
if the instance of an NSString that is the receiver "doesn’t begin
with a valid text representation of a floating-point number." Is
there a simple way to distinguish between the string 0.0, which
shouldn't be considered illegitimate for my purposes, and the string
(for example) X0.0 other than writing extra lines of code to
distinguish one case from the other? I know I could use a scanner,
but perhaps there's something simple that I'm overlooking.
As it happens, I ran into the integer version of this question
yesterday. My pragmatic solution was to trim the string of whitespace,
then test whether the first character was a digit (or a period, or a
minus sign in your case, perhaps, but they may introduce localization
concerns), and go ahead with the string conversion if it is. A bit
hackish, but easier than setting up a NSScanner.
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden