demand
If two decimal places are not 0, keep two decimal places,eg: “0.23” 2. If one decimal place is not 0, keep one decimal place, otherwise display integer, eg: “0.2” “0”, that is, do not appear “0.20”,”0.00″ such situation.
Usually in the development of the project, when formatting decimals by strings, 2 decimals will be reserved. If not, 0 will be used to complete, that is, %.2f will be used as a placeholder in the formatting method to occupy decimals. The resulting string must be something like “x.xx” and will be filled with zeros if there are less than two decimal places.
However, the goose now needs to change, requiring the retention of two decimal places, and can not display 0.
The solution
OC:
/** Filter/to format the.2f string, remove the 0 @param numberstr. 2f formatted string @return*/ - (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];
returnnumberStr; }}}return numberStr;
}else{
returnnil; }}Copy the code
Swift
/// Filters the.2f formatted string and removes the end 0 /// /// -parameter numberString:.2f formatted string 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 ""}}Copy the code
1. Format the decimal number as.2f to 0.00. 2. Then according to the decimal point “.”, cut the string to compare, determine whether the last “0”, if so, directly cut;
The same idea is also applicable to formatting.3f. Add “000” to the judgment method, and then judge the cut string.