如何格式化UInt64.max以添加逗号

时间:2015-06-10 22:17:20

标签: ios swift

我正在尝试格式化为UInt64.max返回的整数,以便为该数字添加逗号。如果它很重要,我现在正在“Playground”中写这个,我正在使用XCode 6.3.2。

以下是相关代码:

//: Playground - noun: a place where people can play

import UIKit

// MARK: - Integer Bounds

var formatter = NSNumberFormatter()
formatter.numberStyle = .DecimalStyle

println( formatter.stringFromNumber(100000) )
println( formatter.stringFromNumber(100000000) )
println( formatter.stringFromNumber( NSNumber(char: Int8.min) ) )

println( Int8.min )
println( Int8.max )

println( UInt8.min )
println( UInt8.max )

println( Int16.min )
println( formatter.stringFromNumber( NSNumber(short: Int16.min) ) )
println( Int16.max )
println( formatter.stringFromNumber( NSNumber(short: Int16.max) ) )

println( UInt16.min )
println( UInt16.max )
println( formatter.stringFromNumber( NSNumber(unsignedShort: UInt16.max) ) )

println( Int32.min )
println( formatter.stringFromNumber( NSNumber(int: Int32.min) ) )
println( Int32.max )
println( formatter.stringFromNumber( NSNumber(int: Int32.max) ) )

println( UInt32.min )
println( UInt32.max )
println( formatter.stringFromNumber( NSNumber(unsignedInt: UInt32.max) ) )

println( Int64.min )
println( formatter.stringFromNumber( NSNumber(longLong: Int64.min) ) )
println( Int64.max )
println( formatter.stringFromNumber( NSNumber(longLong: Int64.max) ) )

println( UInt64.min ) // 0
println( UInt64.max ) // 18446744073709551615
println( formatter.stringFromNumber( NSNumber(unsignedLongLong: UInt64.max) ) ) // Optional("-1")

除了最后一个(UInt64.max)之外,所有这些都返回格式正确的数字。

如图所示,最后一行(我尝试使用格式化程序添加逗号)返回Optional("-1")

如何打印用逗号格式化的UInt64.max

1 个答案:

答案 0 :(得分:0)

在Obj-C中(以防万一):

NSNumber *num = [NSNumber numberWithDouble:18446744073709551615.];

NSNumberFormatter *formatter;
formatter = [[NSNumberFormatter alloc] init];

formatter.numberStyle = kCFNumberFormatterDecimalStyle;
[formatter setMaximumFractionDigits:0];
[formatter stringFromNumber:num];

NSString *formattedString = [formatter stringFromNumber:num];

NSLog(@"%@", formattedString);

结果18,446,744,073,709,600,000

在Swift中

    var num = 18446744073709551615.0

    var formatter = NSNumberFormatter()
    formatter.numberStyle = .DecimalStyle
    formatter.maximumFractionDigits = 0
    formatter.stringFromNumber(num)

    println(formatter.stringFromNumber(num))

结果可选(" 18,446,744,073,709,600,000")