In my iPhone application, the user can change the unit (km or mile) in the preferences.
[[NSUserDefaults standardUserDefaults] setObject:@"km" forKey:@"distanceUnit"];
or
[[NSUserDefaults standardUserDefaults] setObject:@"mile" forKey:@"distanceUnit"];
I save the distance only in km in my Core-Data. I work with int. So every time I get the distance i do the following:
if ([unit isEqualToString:@"km"]) {
} else {
intTotalKM = intTotalKM * 0.621371192;
}
And when saving the distance, I do the following:
if ([unit isEqualToString:@"km"]) {
} else {
intTotalKM = intTotalKM / 0.621371192;
}
For example, without changing my distance, when I save and get it, I loose 1 or 2 km/miles.
I loose precision because of 0.621371192 and because I’m using only int. I don’t want to use double values. Do you have any ideas of how to deal with this problem?
Edit: I wonder if there is any other way of conversion more appropriate for my situation.
Thanks.
If the loss of precision that you have by converting the number one time is acceptable, then I would just quit converting back and forth every time that you display/save it, and only convert, if needed, when the value is entered by the user.
So in other words, just like in your user defaults, only ever have the value in memory represent km.
Note that this conversion is only done once when the user enters a new value.
To display the value to the user, you would convert the value to miles if needed. When you save the value, you simply save intTotalKM without doing any conversion since it is always stored in KM.
Otherwise, you should store the value in such a way that you won’t have this loss of precision. By storing the decimal portion of the number (using a double), by saving as a different unit (like meters – my personal favorite) or by storing the unit and using native values, all as suggested in other answers here.