在APP设计中,货币金额计算经常用到,但经常会遇到四舍五入问题,比如在输入框中输入99999999.99的时候,在计算和之后,得到的值不匹配,比如99999999.99 * 2 = 2000000000.00这样的问题。
通常做法如下:
NSString *count = 2;// 物品数量
NSString *price = @"999999999.99"; // 物品单价
NSString *singleTotlePrice = [NSString stringWithFormat:@"%.2f", (double)[price doubleValue]];
double total = [count doubleValue] * [singleTotlePrice doubleValue];
NSLog(@"%.2f",total); // 保留两位 199999999.98
singleTotalPriceTextLab.text = [NSString stringWithFormat:@"小计(元):¥%.2lf",total];
输入控制部分,比如输入小数点前8位,小数点后2位,只需在UITextField的代理方法中调用工具方法即可,实现如下:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
// 实际付款金额位数限制,小数点前是 8为整数,小数点后2位
return [DCFCustomExtra limitPayMoneyDot:textField shouldChangeCharactersInRange:range replacementString:string dotPreBits:8 dotAfterBits:2];
}
/**
* 付款金额限制代码
*
* @param textField 当前textField
* @param range range
* @param string string
* @param dotPreBits 小数点前整数位数
* @param dotAfterBits 小数点后位数
*
* @return shouldChangeCharactersInRange 代理方法中 可以限制金额格式
*/
+ (BOOL) limitPayMoneyDot:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string dotPreBits:(int)dotPreBits dotAfterBits:(int)dotAfterBits
{
if ([string isEqualToString:@"\n"]||[string isEqualToString:@""])
{ //按下return
return YES;
}
NSCharacterSet *cs;
NSUInteger nDotLoc = [textField.text rangeOfString:@"."].location;
if (NSNotFound == nDotLoc && 0 != range.location)
{
cs = [[NSCharacterSet characterSetWithCharactersInString:myNumbers]invertedSet];
if ([string isEqualToString:@"."])
{
return YES;
}
if (textField.text.length >= dotPreBits)
{ //小数点前面6位
// [textField resignFirstResponder];
[DCFStringUtil showNotice:[NSString stringWithFormat:@"只允许小数前%d位", dotPreBits]];
return NO;
}
}
else
{
cs = [[NSCharacterSet characterSetWithCharactersInString:myDotNumbers]invertedSet];
if (textField.text.length >= dotPreBits + dotAfterBits + 1)
{
[textField resignFirstResponder];
[DCFStringUtil showNotice:[NSString stringWithFormat:@"只允许小数点后%d位", dotAfterBits]];
return NO;
}
}
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
BOOL basicTest = [string isEqualToString:filtered];
if (!basicTest)
{
[textField resignFirstResponder];
[DCFStringUtil showNotice:[NSString stringWithFormat:@"只允许小数点后%d位", dotAfterBits]];
return NO;
}
if (NSNotFound != nDotLoc && range.location > nDotLoc +2)
{ //小数点后面两位
[textField resignFirstResponder];
[DCFStringUtil showNotice:[NSString stringWithFormat:@"只允许小数点后%d位", dotAfterBits]];
return NO;
}
return YES;
}
本文已在版权印备案,如需转载请在版权印获取授权。
获取版权