I know this has been asked a few times in the past but everything I try is failing. I have a custom numeric keypad with a UILabel. When I hit the '1' the UILabel displays a one. Now here's what I'm trying to do:
Now the keyboard and UILabel are working great. I just need to get the decimal's working now. Any sample code would be great, (and where I should place it in my application). Let me know if you want to see my code thus far. Pretty straightforward. Thanks everyone!
Here's about how I would do it:
#define NUMBER_OF_DECIMAL_PLACES 2
NSMutableArray *typedNumbers = ...; //this should be an ivar
double displayedNumber = 0.0f; //this should also be an ivar
//when the user types a number...
int typedNumber = ...; //the number typed by the user
[typedNumbers addObject:[NSNumber numberWithInt:typedNumber]];
displayedNumber *= 10.0f;
displayedNumber += (typedNumber * 1e-NUMBER_OF_DECIMAL_PLACES);
//show "displayedNumber" in your label with an NSNumberFormatter
//when the user hits the delete button:
int numberToDelete = [[typedNumbers lastObject] intValue];
[typedNumbers removeLastObject];
displayedNumber -= (numberToDelete * 1e-NUMBER_OF_DECIMAL_PLACES);
displayedNumber /= 10.0f;
//show "displayedNumber" in your label with an NSNumberFormatter
Typed in a browser. Caveat Implementor. Bonus points for using NSDecimal
instead of a double
.
Explanation of what's going on:
We're essentially doing bit shifting, but in base 10 instead of base 2. When the user types a number (ex: 6), we "shift" the existing number left one decimal place (ex: 0.000 => 00.00), multiply the typed number by 0.01 (6 => 0.06), and add that to our existing number (00.00 => 00.06). When the user types in another number (ex: 1), we do the same thing. Shift left (00.06 => 00.60), multiply the typed number by 0.01 (1 => 0.01), and add (00.60 => 00.61). The purpose of storing the number is an NSMutableArray
is simply a convenience to make deletion easier. It's not necessary, however. Just a convenience.
When the user hits the delete button (if there is one), we take the last number entered (ex: 1), multiply it be 0.01 (1 => 0.01), subtract it from our number (0.61 => 0.6), and then shift our number right one decimal place (0.6 => 0.06). Repeat this as long as you've got numbers in your array of entered numbers. Disable the delete button when that array is empty.
The suggestion to use NSDecimal
is simply to allow for very high precision numbers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With