如題的需求,再詳細解釋一下就是: 1.若是有兩位小數不爲0則保留兩位小數,eg: "0.23" 2.若是有一位小數不爲0則保留一位小數,不然顯示整數, eg: "0.2" "0" 也就是說,不能出現"0.20","0.00"這種狀況。bash
平時在項目開發中,格式化小數乘字符串是時候,常常會保留2位小數處理,不足則用0補全,也就是在格式化方法中用 %.2f 做佔位符,來佔位小數。這樣得出來的字符串確定是相似"X.XX"的字符串,且若是不足兩位小數,都會用0來補全。ui
然鵝如今的需求變了,要求保留兩位小數,且能不顯示0就不顯示。spa
OC:code
/**
過濾器/ 將.2f格式化的字符串,去除末尾0
@param numberStr .2f格式化後的字符串
@return 去除末尾0以後的
*/
- (NSString *)removeSuffix:(NSString *)numberStr{
if (numberStr.length > 1) {
if ([numberStr componentsSeparatedByString:@"."].count == 2) {
NSString *last = [numberStr componentsSeparatedByString:@"."].lastObject;
if ([last isEqualToString:@"00"]) {
numberStr = [numberStr substringToIndex:numberStr.length - (last.length + 1)];
return numberStr;
}else{
if ([[last substringFromIndex:last.length -1] isEqualToString:@"0"]) {
numberStr = [numberStr substringToIndex:numberStr.length - 1];
return numberStr;
}
}
}
return numberStr;
}else{
return nil;
}
}
複製代碼
Swiftcomponent
/// 過濾器 將.2f格式化的字符串,去除末尾0
///
/// - Parameter numberString: .2f格式化後的字符串
/// - Returns: 去除末尾0以後的
func removeSuffix(numberString : String) -> String {
if numberString.count > 1 {
let strs = numberString.components(separatedBy: ".")
let last = strs.last!
if strs.count == 2 {
if last == "00" {
let indexEndOfText = numberString.index(numberString.endIndex, offsetBy:-3)
return String(numberString[..<indexEndOfText])
}else{
let indexStartOfText = numberString.index(numberString.endIndex, offsetBy:-1)
let str = numberString[indexStartOfText...]
let indexEndOfText = numberString.index(numberString.endIndex, offsetBy:-1)
if str == "0" {
return String(numberString[..<indexEndOfText])
}
}
}
return numberString
}else{
return ""
}
}
複製代碼
思路:1.先將小數按照.2f格式化處理成「0.00」; 2.而後再根據小數點".",切割字符串比較,判斷最後的是否是「0」,是的話,直接切除掉;開發
一樣思路的也適用於格式化.3f的狀況,判斷方法中再加入「000」的判斷,而後判斷切割後的字符串。rem