2011-07-11 25 views
1
label.text = [NSString stringWithFormat:@"%.2f",final]; 

上記のステートメントは、変数 "final"で使用可能なfloat値を小数点以下2桁で表示します。カスタム浮動小数点

私は私がここでjは整数の変数である。この

label.text = [NSString stringWithFormat:@"%.if",j,final] 

のような整数の変数に与えてきた数に応じで小数点以下の桁数を表示したいです。私がjのために取った数が何であれ、それは多くの小数点が表示されるはずです。上記のステートメントを表示するには適切な構文が必要です。

+0

明確にします。どのような出力が必要ですか。 Jの価値は何ですか?最終的な価値は何ですか?あなたが出力として望むもの。 –

答えて

0

あなたがやりたいだろうワンライナーがあるかどうかは分かりませんが、あなたは常に行うことができます。

NSString* formatString = [NSString stringWithFormat: @"%%.%if", j]; 
label.text = [NSString stringWithFormat:formatString, final]; 
+0

ありがとうございました – Uday

2

NSNumberFormatterは、あなたが欲しいものを行う能力を持っています。文字列を書式設定する前に、変数を使用して次のいずれかの方法を設定できます。

- (void)setMinimumIntegerDigits:(NSUInteger)number 
- (void)setMinimumFractionDigits:(NSUInteger)number 
- (void)setMaximumIntegerDigits:(NSUInteger)number 
- (void)setMaximumFractionDigits:(NSUInteger)number 

Data Formatting Guide - Number Formatters

0

あなたはApple follows状態というNSNumberFormatter

NSNumberFormatter *nf = [[NSNumberFormatter alloc] init]; 
[nf setFormatterBehavior:NSNumberFormatterBehaviorDefault]; 
[nf setNumberStyle:NSNumberFormatterDecimalStyle]; 
[nf setMaximumFractionDigits:j]; // Set the number of decimal places here 

label.text = [nf stringFromNumber:[NSNumber numberWithFloat:final]]; 

[nf release]; 
4

IEEE printf specを使用することができます。

フィールド幅、または精度、またはその両方があってもよいですアスタリスク0で示される( '*')この場合、int型の引数はフィールド幅 または精度を提供します。

これは

label.text = [NSString stringWithFormat:@"%.*f",j,final] 

はうまくいくかもしれないが、私は今それをテストするために利用可能なプラットフォームを持っていないことを意味します。

+0

+1!うわー!すばらしいです! – EmptyStack

+0

+1すてきな答え! – Joe

+0

+1以前は精度のためにそれを行うことはできませんでした。 – JeremyP

関連する問題