Baidyanath
Baidyanath

Reputation: 177

convert NSString TO NSNumber accurately with decimal

Lets say my string value is as follows 12345.12 after converting it to NSNumber its coming as 12345.1223122 But I want the accurate number from string Is there a way to achieve it. Code that I'm using right now

NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
    [f setNumberStyle:NSNumberFormatterCurrencyStyle];
    NSNumber * myNumber = [f numberFromString:aString];
    [f release];

Upvotes: 0

Views: 3193

Answers (4)

user8527410
user8527410

Reputation: 493

It's a few years, but this works:

double d = [@"123.45" doubleValue];
NSNumber* n = [NSNumber numberWithDouble:d];

Upvotes: 0

Paresh Navadiya
Paresh Navadiya

Reputation: 38239

Do this:

NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
[f setMaximumFractionDigits:2];
NSNumber * myNumber = [f numberFromString:aString];
[f release];
NSLog(@"%@",myNumber);

Upvotes: 1

Prasad G
Prasad G

Reputation: 6718

Try Like this...

 NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterCurrencyStyle];
NSNumber * myNumber=[NSNumber numberWithFloat:[[f numberFromString:aString] floatValue]];

I think it will be helpful to you.

Upvotes: 1

Tommy
Tommy

Reputation: 100622

If you're dealing with currency-type numbers (just a guess from your use of the currency style formatter) you probably want to use NSDecimalNumber. Unlike standard floating point types, decimal numbers use a base-10 exponent so that you always get exactly the expected accuracy when dealing with money problems — i.e. they're the same as using integers and then moving the decimal point around in the base-10 representation.

Upvotes: 3

Related Questions