Question

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

So I've created an segmented control with "0", "1", "2" and "3". I want to set the digits after the comma with a variable (self._segmentedControl.selectedSegmentIndex).

I know that I can decide how many digits after a comma should be like this:

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

Can someone please help me?

Was it helpful?

Solution

You can even do it in one step:

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

OTHER TIPS

You could do this in two steps.

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

This should do the trick. Beware of format string attacks.

Check whether this works or not. I only tested this with C++, but since the documentation for String Format points to IEEE printf specification, I believe it should also work for Objective-C.

sliderValue.text = [NSString stringWithFormat: @"%.*f", places, slider.value];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top