2017-10-13 62 views
1

您好,我需要格式化用戶在應用程序中輸入的十進制數字。使用NSNumberFormatter格式化十進制數字

100. = 100 
90.00 = 90 
90.1 = 90.1 
90.22 = 90.22 
90.227 = 90.23 

我應該如何使用NSNumberFormatter來實現這一點。

我取得相同的,如果其他條件

if ([cell.textField.text rangeOfString:@"."].location != NSNotFound) 
    { 
     NSString *strAfterDecimal = [cell.textField.text componentsSeparatedByString:@"."].lastObject; 
     NSInteger count = [strAfterDecimal length]; 

     if(count == 0) 
     { 
      customField.value = [cell.textField.text 
           stringByReplacingOccurrencesOfString:@"." withString:@""]; 
     } 
     else if(count == 1 || count == 2) 
     { 
      if([strAfterDecimal integerValue] > 0) 
      { 
       customField.value = cell.textField.text; 
      } 
      else 
      { 
       customField.value = [cell.textField.text componentsSeparatedByString:@"."].firstObject; 
      } 
     } 
     else if(count > 2) 
     { 
      if([strAfterDecimal integerValue] > 0) 
      { 
       customField.value = [NSString stringWithFormat:@"%0.2f",[cell.textField.text floatValue]]; 
      } 
      else 
      { 
       customField.value = [cell.textField.text componentsSeparatedByString:@"."].firstObject; 
      } 
     } 
    } 

我需要consize的代碼中使用這個自定義。至於根據客戶我不能把額外的代碼,如果蘋果給出的默認功能做的事情

回答

2

這是非常簡單的

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; 
formatter.maximumFractionDigits = 2; 
NSNumber *number = [formatter numberFromString:cell.textField.text]; 
NSString *numberString = [formatter stringFromNumber:number]; 
if (numberString == nil) numberString = @"0"; 
NSLog(@"%@", numberString); 

雨燕的版本是一個比較複雜一點,因爲你必須安全地解開了自選

let formatter = NumberFormatter() 
formatter.maximumFractionDigits = 2 
let numberString : String 
if let text = cell.textField.text, 
    let number = formatter.number(from: text), 
    let string = formatter.string(from: number) { 
    numberString = string 
} else { 
    numberString = "0" 
} 
print(numberString) 
+0

這是否解決了以下要求:「90.00 = 90」? – sketchyTech

+0

@sketchyTech是的,它確實 – vadian

+0

非常感謝@vadian。它拯救了我的一天。它按照我的要求工作。再次感謝。 :) –