Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone: How many digits should be after a dot of a float

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?

like image 953
MaxB Avatar asked Sep 19 '12 17:09

MaxB


People also ask

How many decimal places does float go to?

The float data type has only 6-7 decimal digits of precision. That means the total number of digits, not the number to the right of the decimal point.

How do you round a float to 2 decimal places in Swift?

Rounding Numbers in SwiftBy using round(_:) , ceil(_:) , and floor(_:) you can round Double and Float values to any number of decimal places in Swift.


2 Answers

You can even do it in one step:

sliderValue.text = [NSString stringWithFormat:@"%.*f", numberOfDigits, slider.value];
like image 125
Martin R Avatar answered Sep 23 '22 18:09

Martin R


You could do this in two steps.

NSString *format = [NSString stringWithFormat:@"%%.%df", numberOfDigits);
sliderValue.text = [NSString stringWithFormat:format, slider.value];
like image 45
DrummerB Avatar answered Sep 22 '22 18:09

DrummerB