美文网首页
给数字加千分位和小数点

给数字加千分位和小数点

作者: 土豆小窝瓜 | 来源:发表于2017-07-21 16:38 被阅读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;

}

/**

  • 整数部分每隔3个字符加一个千分位
  • @param number 数字
  • @return 千分位数字
    */

{
+ (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;
}

}

相关文章

网友评论

      本文标题:给数字加千分位和小数点

      本文链接:https://www.haomeiwen.com/subject/qmuekxtx.html