Question

I can't see to find the answer to this, but I have a string that has a decimal point in it, and when I try to convert it to a NSDecimalNumber I only get back the whole number, not the decimal or what would come after it. This is what I am trying:

someText.text = @"200.00";
tempAmountOwed = [NSDecimalNumber decimalNumberWithString:someText.text]; // gives me back 200

I can't seem to figure out if the decimalNumberWithString method is stripping out my decimal and ignoring what comes after it.

Thanks for the help!

Était-ce utile?

La solution

You can use the method decimalNumberWithString: locale: method.

for eg:-

The code:

NSLog(@"%@", [NSDecimalNumber decimalNumberWithString:@"200.00"]);
NSLog(@"%@", [NSDecimalNumber decimalNumberWithString:@"200.00" locale:NSLocale.currentLocale]);

Gives following log:

200
200.00

Hope this Helps!

Autres conseils

That's perfectly normal. If your decimal String doesn't contain fractions it won't print them. If you want to print them you can use a NSNumberFormatter or convert it to a float and print it with %.2f to do so:

NSString *text = @"200.00";
NSDecimalNumber *number = [NSDecimalNumber decimalNumberWithString:text];
NSLog(@"%@", number); //this will print "200"

//solution #1
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
numberFormatter.numberStyle = NSNumberFormatterDecimalStyle;
numberFormatter.minimumFractionDigits = 2;
NSLog(@"%@", [numberFormatter stringFromNumber:number]); //this will print "200.00"

//solution #2
CGFloat number = [text floatValue];
NSLog(@"%.2f", number); //this will print "200.00"
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top