给数字加千分位和小数点

2017-07-21  本文已影响30人  土豆小窝瓜

{
* 设置千分位
例如
* 1111.120 = 1,111.12
1111.102 = 1,111.1
1111.00 = 1,111
1111 = 1,111

 *  @param number 原来的数字
 *
 *  @return 设置完千分位后的数字
 */
+ (NSString *)addPoint:(NSString *)number
{
    if ([number rangeOfString:@"."].location != NSNotFound)
    {
        NSArray *array  = [number componentsSeparatedByString:@"."];
        if (array.count>=1)
        {
            NSString *str = [array lastObject];
            if ([str floatValue] == 0)
            {
                number = [array firstObject];
                number = [self setPoint:number];
            }
            else
            {
                if (str.length>2)
                {
                    number = [NSString stringWithFormat:@"%.2f",[number doubleValue]];
                }
                NSString *lastStr = [number substringFromIndex:number.length-1];
                if ([lastStr isEqualToString:@"0"])
                {
                    number = [NSString stringWithFormat:@"%.1f",[number doubleValue]];
                }
                
                NSArray *newArray = [number componentsSeparatedByString:@"."];
                if (newArray.count > 1)
                {
                    NSString *firstStr = newArray[0];
                    NSString *twoStr = [newArray lastObject];
                    firstStr = [self setPoint:firstStr];
                    number  = [NSString stringWithFormat:@"%@.%@",firstStr,twoStr];
                }
            }
        }
    }
    else
    {
        number = [self setPoint:number];
    }
    return number;

}

/**

{
+ (NSString *)setPoint:(NSString *)number
{
NSString *doneTitle = @"";
int count = 0;
for (NSInteger i = number.length-1; i >= 0; i--)
{

        count++;
        doneTitle = [doneTitle stringByAppendingString:[number substringWithRange:NSMakeRange(i, 1)]];
        if (count == 3)
        {
            if (i==0)
            {
                doneTitle = [NSString stringWithFormat:@"%@", doneTitle];
            }
            else
            {
                doneTitle = [NSString stringWithFormat:@"%@,", doneTitle];
            }
            count = 0;
        }
    }
    NSMutableString * reverseString = [NSMutableString string];
    for(int i = 0 ; i < doneTitle.length; i ++)
    {
        unichar c = [doneTitle characterAtIndex:doneTitle.length- i -1];
        [reverseString appendFormat:@"%c",c];
    }
    doneTitle = reverseString;
    return doneTitle;
}

}

上一篇 下一篇

猜你喜欢

热点阅读