IPhone: how many digits should be after the float

I am trying to set the number of digits of a float with a segmented control.

So, I created a segmented control with "0", "1", "2" and "3". I want to set decimal digits with variable ( self._segmentedControl.selectedSegmentIndex).

I know that I can decide how many digits after the decimal point should be like this:

sliderValue.text = [NSString stringWithFormat:@"%.3f",slider.value];

Can anyone help me out?

+5
source share
4 answers

You can do this in one step:

sliderValue.text = [NSString stringWithFormat:@"%.*f", numberOfDigits, slider.value];
+7
source

You can do this in two steps.

NSString *format = [NSString stringWithFormat:@"%%.%df", numberOfDigits);
sliderValue.text = [NSString stringWithFormat:format, slider.value];
+2
source
NSString *format = [NSString stringWithFormat:@"%%.%df", numberOfDecimalPlaces];
sliderValue.text = [NSString stringWithFormat:format, slider.value];

. .

+2

Check if it works or not. I tested this only in C ++, but since the documentation for String Format points to IEEE printf , I believe that it should work for Objective-C as well.

sliderValue.text = [NSString stringWithFormat: @"%.*f", places, slider.value];
+1
source

All Articles