有时候我们希望把小数显示出来,但 NSNumber 的 stringValue 方法默认会输出便于阅读的格式,如下:
NSDecimalNumber \*dn = [NSDecimalNumber decimalNumberWithString:@"0.0001"];
NSString *s = [dn stringValue]; // s will be @"1E-4"
可以使用如下方法:
Double 转换为 String
func getStringFrom(double doubleVal: Double) -> String
{
var stringValue : String = "0.00"
let formatter = NSNumberFormatter()
formatter.usesSignificantDigits = true;
formatter.maximumSignificantDigits = 100
formatter.groupingSeparator = "";
formatter.numberStyle = .DecimalStyle
stringValue = formatter.stringFromNumber(doubleVal)!;
return stringValue
}
String 转换为 Double
func getDoubleFrom(textField textField: UITextField) -> Double
{
var doubleValue : Double = 0.0
if let val = textField.text
{
let numberFormatter = NSNumberFormatter()
numberFormatter.numberStyle = NSNumberFormatterStyle.DecimalStyle
let finalNumber = numberFormatter.numberFromString(val)
doubleValue = (finalNumber?.doubleValue)!;
}
return doubleValue
}
Objective-C 版本
-(NSString*)getStringFrom:(double)doubleVal {
NSString* stringValue = @"0.00";
NSNumberFormatter *formatter = [[NSNumberFormatter alloc]init];
formatter.usesSignificantDigits = true;
formatter.maximumSignificantDigits = 100;
formatter.groupingSeparator = @"";
formatter.numberStyle = NSNumberFormatterDecimalStyle;
stringValue = [formatter stringFromNumber:@(doubleVal)];
return stringValue;
}