我有一个双精度值,即22.368511,我想将其四舍五入到小数点后两位。即它应该返回22.37
我怎样才能做到这一点?
我有一个双精度值,即22.368511,我想将其四舍五入到小数点后两位。即它应该返回22.37
我怎样才能做到这一点?
Answers:
与大多数语言一样,格式为
%.2f
你可以在这里看到更多的例子
编辑:如果您担心点的显示在25.00的情况下,我也得到了
{
NSNumberFormatter *fmt = [[NSNumberFormatter alloc] init];
[fmt setPositiveFormat:@"0.##"];
NSLog(@"%@", [fmt stringFromNumber:[NSNumber numberWithFloat:25.342]]);
NSLog(@"%@", [fmt stringFromNumber:[NSNumber numberWithFloat:25.3]]);
NSLog(@"%@", [fmt stringFromNumber:[NSNumber numberWithFloat:25.0]]);
}
2010-08-22 15:04:10.614 a.out[6954:903] 25.34 2010-08-22 15:04:10.616 a.out[6954:903] 25.3 2010-08-22 15:04:10.617 a.out[6954:903] 25
setPositiveFormat:
,因为setFormat:
方法不存在(仅为Mac定义),但仍然-很好的答案,节省了我很多时间的实验,因此+1并非常感谢您:)
您可以使用以下代码将其格式化为两位小数
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMaximumFractionDigits:2];
[formatter setRoundingMode: NSNumberFormatterRoundUp];
NSString *numberString = [formatter stringFromNumber:[NSNumber numberWithFloat:22.368511]];
NSLog(@"Result...%@",numberString);//Result 22.37
斯威夫特4:
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 2
formatter.roundingMode = .up
let str = String(describing: formatter.string(from: 12.2345)!)
print(str)
value = (round(value*100)) / 100.0;
要从双精度数中删除小数,请查看此输出
对象C
double hellodouble = 10.025;
NSLog(@"Your value with 2 decimals: %.2f", hellodouble);
NSLog(@"Your value with no decimals: %.0f", hellodouble);
输出将是:
10.02
10
Swift 2.1和Xcode 7.2.1
let hellodouble:Double = 3.14159265358979
print(String(format:"Your value with 2 decimals: %.2f", hellodouble))
print(String(format:"Your value with no decimals: %.0f", hellodouble))
输出将是:
3.14
3
我本来打算用Jason的答案,但是我注意到在我的Xcode版本(4.3.3)中,我无法做到这一点。因此,经过一番研究,我发现他们最近更改了类方法,并删除了所有旧方法。所以这是我必须做的:
NSNumberFormatter *fmt = [[NSNumberFormatter alloc] init];
[fmt setMaximumFractionDigits:2];
NSLog(@"%@", [fmt stringFromNumber:[NSNumber numberWithFloat:25.342]]);
使用NSNumber * aNumber = [NSNumber numberWithDouble:number]; 而不是NSNumber * aNumber = [NSNumber numberWithFloat:number];
+(NSString *)roundToNearestValue:(double)number
{
NSNumber *aNumber = [NSNumber numberWithDouble:number];
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setUsesGroupingSeparator:NO];
[numberFormatter setMaximumFractionDigits:2];
[numberFormatter setMinimumFractionDigits:0];
NSString *string = [numberFormatter stringFromNumber:aNumber];
return string;
}
我使用Umberto Raimondi 扩展类型Double 张贴的解决方案:
extension Double {
func roundTo(places:Int) -> Double {
let divisor = pow(10.0, Double(places))
return (self * divisor).rounded() / divisor
}
}