ios - NSDecimalNumber for finances -
i'm building app deals money , i've been using floating point arithmetic until now, i've learned it's better use nsdecimalnumber.
i want make sure i've understood correctly, here goes:
imagine worker, earning 20.57$/hour. information provided user. did before:
@property (nonatomic) float hourlyrate; nsnumberformatter *numberformatter = [[nsnumberformatter alloc] init]; numberformatter.numberstyle = nsnumberformatterdecimalstyle; nsnumber *hourlyrate = [numberformatter numberfromstring:self.ratetextfield.text]; settingsobject.hourlyrate = [hourlyrate floatvalue];
but i've changed to:
@property (nonatomic) nsdecimalnumber *hourlyrate; settingsobject.hourlyrate = (nsdecimalnumber *)[nsdecimalnumber decimalnumberwithstring:self.ratetextfield.text locale:[nslocale currentlocale]];
is correct way read nsdecimalnumbers string?
say person enters workplace @ 10:01. save information so:
[[nsuserdefaults standarduserdefaults] setobject:[nsdate date] forkey:@"start"];
once person finished, start time read nsuserdefaults so:
nsdate *start = [[nsuserdefaults standarduserdefaults] objectforkey:@"start"];
the duration calculated so:
nstimeinterval interval = [[nsdate date] timeintervalsincedate:start] / 3600; nsdecimalnumber *earned = [settingsobject.hourlyrate decimalnumberbymultiplyingby:[[nsdecimalnumber alloc] initwithfloat:interval]];
is correct , efficient way, while keeping precision?
thanks!
is correct way read nsdecimalnumbers string?
yes. however, shouldn't need cast result. should this:
settingsobject.hourlyrate = [nsdecimalnumber decimalnumberwithstring:self.ratetextfield.text locale:[nslocale currentlocale]];
and nslocale
part isn't necessary, unless you're using non-current locale:
settingsobject.hourlyrate = [nsdecimalnumber decimalnumberwithstring:self.ratetextfield.text];
i don't think function likes nil values, want make sure ratetextfield
has non-nil value first:
if ([self.ratetextfield hastext]) { settingsobject.hourlyrate = [nsdecimalnumber decimalnumberwithstring:self.ratetextfield.text]; } else { settingsobject.hourlyrate = [nsdecimalnumber zero]; }
is correct , efficient way, while keeping precision?
yes, conversion of interval nsdecimal number , multiplication looks me.
Comments
Post a Comment