2012-07-06 80 views
0

我想檢查一個浮點變量的數字長度,但我不知道要使用的正確語法。我看了這個,我找不到答案。檢查一個浮點數的長度

我的代碼是一個簡單的if語句:從長度

NSString *stringNumber = [NSString stringWithFormat:@"%g", currentValue]; 
int length = stringNumber.length 

你或許可以減去1:

if (currentNumber.digits < 3) { //If the number has less that three digits, I don't know what to put here to get it working 

    //code 
} 
+1

你說的長度是什麼意思?你的意思是小數點前的數字嗎?只是之後的?或者全部都是? – Jodaka 2012-07-06 17:04:13

+0

對不起,只是小數點前的那個。 – Fernald 2012-07-06 17:04:52

+2

您可以四捨五入(小數)十進制日誌來獲取您的位數。 – 2012-07-06 17:06:20

回答

2
#include <math.h> 

//... 

int digits = (int) ceil(log10(number)); 

額外的邏輯爲負數就留給讀者做練習。

+1

不可以。請參閱頂部或我的回答評論。你必須整理,而不是放下,以獲得數字的位數。 – 2012-07-06 17:17:27

+0

工作!謝謝! – Fernald 2012-07-06 17:17:56

+0

@dystroy感謝您的更正 – 2012-07-06 18:23:29

0

你可以做一個的NSString與你的價值和檢查的長度考慮小數點。

Here'sNSString doc的參考資料,以便您可以檢查這些方法的作用,以防您不瞭解它們。

編輯:如果你想在小數點前面你也可以在我貼出這樣做的數字:

[stringNumber substringToIndex:[stringNumber rangeOfString:@"."].location].length 

然後在有條件的程序使用此值。

0
int digits = [[NSString stringWithFormat:@"%g", variable] length] 
-6
int myInt = (int) myFloat; 

sizeof(myint) 
+8

很簡單,不。 – 2012-07-06 17:07:46

2

由於那裏似乎不是一個正確的答案:

int digits = (int) ceil(log10(currentNumber));