Idrees Ashraf
Idrees Ashraf

Reputation: 1383

NSString to NSNumber ignores initial zeros

I am converting NSString to NSNumber. But the problem is that if NSString starts with zeros then converting it to NSNumber ignores the initial zeros. I know initial zeros doesn't mean anything but I want to keep initial zeros because it's phonenumber in my case.

here is my code:

NSLog(@"test1: %@",tempPhoneNumber);
NSNumberFormatter *formatter=[[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber *tempPnoneNumberNumber=[formatter numberFromString:tempPhoneNumber];
NSLog(@"test: %@",tempPnoneNumberNumber);

if test1: 00966123456789 then test: 966123456789

I want both same

Upvotes: 1

Views: 678

Answers (4)

colincameron
colincameron

Reputation: 2703

If you're not doing calculations with it then it's a string, not a number.

This applies to phone numbers, zip codes, etc.

If you do manage to store leading zeros then someone will eventually come along with this phone number: +44 (0)1234 567890 - how will you deal with that?

Upvotes: 1

Burhanuddin Sunelwala
Burhanuddin Sunelwala

Reputation: 5343

There are two ways you can accomplish this: first, if your phone number is of fixed size then you can use this

NSLog(@"test %014d", tempPnoneNumberNumber);

else just add leading zeros by

[formatter setPaddingCharacter:@"00"];

Upvotes: 0

Sulthan
Sulthan

Reputation: 130092

NSNumber cannot keep initial zeros.

If you want to keep the zeros, don't convert it to NSNumber. Phone numbers are not actually numbers, there are usually kept as strings.

Also note that phonenumbers can contain other characters: +, * or #. These characters often have special meaning (e.g. + at the beginning means the same as 00).

Upvotes: 4

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726499

If you know how many digits a number must have, you can format it to the required number of digits with optional leading zeros by using the "%014lli" format. The magic number 14 is the required number of digits, including the leading zeros. Here is a link to a demo in C that uses a long long constant to represent your number.

P.S. Phone numbers are not really "numbers", they are strings that happen to be composed of digits. You should not attempt converting them to numbers precisely because of the leading zeros issue.

Upvotes: 2

Related Questions