开发者

How to truncate .000 zeros from double with NSNumberFormatter

开发者 https://www.devze.com 2023-01-16 10:52 出处:网络
Ok so if I have a double to begin with how do I limit it or truncate digits to 1dp since I know they\'re not needed to be viewed

Ok so if I have a double to begin with how do I limit it or truncate digits to 1dp since I know they're not needed to be viewed

double a = 1.6;

NSNumberFormatter *num开发者_JS百科berFormatter = [[NSNumberFormatter alloc] init];
NSString *numberAsString = [numberFormatter stringFromNumber:[NSNumber numberWithDouble:a]];

[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setGeneratesDecimalNumbers:YES];
[numberFormatter setMaximumFractionDigits:1];
[numberFormatter setMinimumFractionDigits:1];
[numberFormatter setAlwaysShowsDecimalSeparator:YES];  

NSLog(@"a raw: %f", a); //outputs 1.600000

myLabel.text = [NSString stringWithFormat:@"%@",numberAsString];

NSLog(@"Formatted a: %@", numberAsString); //outputs 2

[numberFormatter release];

So the problem is it rounds the value and leaves no decimal place, I'm trying to get it to output just 1.6 for myLabel.


I am not sure but you can try with NSString *formatted = [NSString stringWithFormat:@"%.1f", a];, then use the formatted as the label text

0

精彩评论

暂无评论...
验证码 换一张
取 消