Konstantin Cherkasov
Konstantin Cherkasov

Reputation: 3343

How to display leading zero in double

I need to make NSNumber to display only 4 decimal points. This part of code is works, but it outputs result without leading zero.

double resultRoundToDecimal = [result doubleValue];
    NSNumberFormatter *resultFormatter = [[NSNumberFormatter alloc] init];
    [resultFormatter setRoundingMode:NSNumberFormatterRoundHalfUp];
    [resultFormatter setMaximumFractionDigits:4];
    resultData = [resultFormatter stringFromNumber:[NSNumber numberWithDouble:resultRoundToDecimal]];

For example: 1/3 = .3333

I want: 1/3 = 0.3333

How I can to do this?

Upvotes: 1

Views: 274

Answers (2)

iphonic
iphonic

Reputation: 12719

You could choose to use string formatter too, like below

float val=1./3;

NSString *resultData=[NSString stringWithFormat:@"%0.4f",val];

NSLog(@"Result = %@",resultData);

Upvotes: 2

ddoor
ddoor

Reputation: 5963

Prepend a 0 or use number formatter.

NSString *printStr = @"0";
printStr = [NSString stringByAppendingString: resultData];

Otherwise, you could use a number formatter or something similar. If your just outputting a string why not do that?

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSNumberFormatter_Class/Reference/Reference.html

Upvotes: 0

Related Questions