izk
izk

Reputation: 1199

Format a float to pad with leading spaces

I can get the result I want with leading zeros, but it does not work with spaces.

[NSString stringWithFormat:@"%05.2f", 2.1]; // 02.10

However, the following does not work:

[NSString stringWithFormat:@"% 5.2f", 2.1]; // 2.10

Nor does this:

[NSString stringWithFormat:@"%5.2f", 2.1]; // 2.10

Upvotes: 5

Views: 1906

Answers (2)

nielsbot
nielsbot

Reputation: 16022

I just tried this and it wored:

printf("%s\n", [[ NSString stringWithFormat:@"% 5.2f\n", 2.1 ] UTF8String ] ) ;

which gives

 2.10

which is correct... maybe the problem lies elsewhere?

EDIT

If you aren't using a fixed width font, you can insert tab characters instead with \t

Upvotes: 4

izk
izk

Reputation: 1199

I think my original solution works as does that suggested by @ColWhi and @nielsbot... I think the issue is the font (Helvetica) has narrower spaces than characters...

Upvotes: 1

Related Questions