4

I want to create NSDecimalNumber after dividing 100. I am using following code:

NSDecimalNumber *amountToSendNumber = [number decimalNumberByDividingBy:[NSDecimalNumber decimalNumberWithString:@"100"]];

It gives me correct value if I provide input as 2536 as 25.36. But if I provide input as 2500 then output is 25. I want output as 25.00 without having any rounding off mechanism.

Any Help?

iAsh
  • 447
  • 6
  • 19
  • Your question sounds related to presentation of the number (in a label, for example), however I don't see any presentation code. Please clarify. – Droppy Jul 06 '16 at 08:45
  • check NSString* formattedNumber = [NSString stringWithFormat:@"%.02f", myFloat]; – Nitin Gohel Jul 06 '16 at 08:50
  • I want to use NSDecimalNumber instead of float as there are other operations to perform. – iAsh Jul 06 '16 at 08:53

1 Answers1

5

You need to use NSNumberFormatter while you display a NSDecimalNumber

  NSNumberFormatter *formatter = [NSNumberFormatter new];
  [formatter setMinimumFractionDigits:2];
   NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
  [formatter setLocale:usLocale];
  NSLog(@"%@", [formatter stringFromNumber:amountToSendNumber]);
Bhumit Mehta
  • 16,278
  • 11
  • 50
  • 64
  • It is giving me 25,00 instead of 25.00. Can you help me? – iAsh Jul 08 '16 at 10:35
  • @iAsh (and others) The decimal output format depends on which identifier you use when you init `NSLocal`. With @"en_US" you should get 25.00, but if you use @"sv_SE" for example, you'll get 25,00. – turingtested Aug 24 '17 at 08:41
  • Is this really the best way to do it? Is there any advantage of using NSDecimalNumber? – Ricardo Ruiz Romero Oct 11 '18 at 17:35
  • I have requirement to pass NSnumber as 12.00 to json dictionary. for the cases, 12.32 then all good. for the cased, 12.00 then it returns NSnumber 12 Please advise @bhumit mehta – Narendra G May 26 '22 at 12:00