Peter V
Peter V

Reputation: 2488

More precise square root of a value

To get a square root value of mainlabelString, I am using

- (IBAction)rootPressed:(id)sender
{

    NSString *mainLabelString = mainLabel.text;

    int mainLabelValue = [mainLabelString longLongValue];

    NSString *calculatedValue = [NSString stringWithFormat: @"%f", sqrt(mainLabelValue)];

    mainLabel.text = calculatedValue;

}

And although it does work with numbers such as 88, from which I get 9.380832, it does not for example work with that number, for which it says the square root is 3.000000 (instead of 3.062814).
I tried replacing longLongValue with doubleValue and integerValue but it doesn't change it.
What's wrong?

Upvotes: 0

Views: 1510

Answers (2)

codester
codester

Reputation: 37189

Use NSNumberFormatter it provides very wide range and different styles(Decimaland scientific etc).documentation

Upvotes: 1

Ramy Al Zuhouri
Ramy Al Zuhouri

Reputation: 21976

If the value into the text field is like @"9.0001", getting the long long value truncates the decimal part.You said that you also have tried doubleValue, but I suspect that you did something like this:

int mainLabelValue = [mainLabelString doubleValue]; 

Instead of:

double mainLabelValue = [mainLabelString doubleValue]; 

In the first case the number loses the decimal part too, because an int can't store the decimal part, nor a long long int.
Let me know how you exactly tried to retrieve the double value of the text field.

Upvotes: 3

Related Questions