0

I have an array containing dictionaries. I need to change the value for key "price" to float value with 2 decimal places alone, but the dictionary should remain the same. I tried fetching each price values and replacing them into a mutable array. But I need it in a simpler solution. Thanks in advance.

(
{
    pen =     {
        price = 180.1299;
    };
    pencil =     {
        price = 20.1299;
    };
},
{
    pen =     {
        price = 111.1267;
    };
    pencil =     {
        price = 23.1278;
    };
}
)
Chan
  • 447
  • 1
  • 5
  • 18
  • 2
    Why do you use dictionaries in the first place? Use *objects*. Objective-C is not Javascript. Parse the dictionary into objects, change the values and the encode it back to dictionaries. – Sulthan Aug 04 '17 at 13:17
  • I parsed it, price values are getting changed as 20.129899999999. – Chan Aug 04 '17 at 13:24
  • That's the same value. If you want decimal values with two digits, you will have to write them as a string. – Sulthan Aug 04 '17 at 13:26
  • "I tried fetching each price values and replacing them into a mutable array. But I need it in a simpler solution." - Edit your question to include this code (or at least more about it if it's too long) and explain why you think it's too complicated. That will help people to help you. – CRD Aug 04 '17 at 17:01
  • You could save your values as NSString and use https://stackoverflow.com/questions/560517/make-a-float-only-show-two-decimal-places And continue use your NSdictionary as a Key/Value store as intended, without doing all the other extra work suggested above, even if in the long term you would benefit more from clean object oriented setup. –  Aug 04 '17 at 20:53
  • Never, ever use float instead of double unless you have a reason to do so that you can explain. – gnasher729 Aug 05 '17 at 14:25

1 Answers1

0

Simple solutions

float  price = 180.1299;
NSString *strRoundPriceVal = [NSString stringWithFormat:@"%.2f",price];
NSLog(@"The Rounded Price Value is - %@",strRoundPriceVal);

Output

enter image description here

user3182143
  • 9,459
  • 3
  • 32
  • 39