2011-08-12 87 views
2

我有一個要求,我應該允許小數位前最多14位數字,小數位後最多4位數字。使用javascript計算小數位數前後的位數

有沒有一種方法可以讓用戶知道他是否輸入222222222222222.222 - 十進制之前的15個數字一旦使用javascript超出該文本框就無效。

我試過,但它並沒有幫助我

MynewTextBox.Attributes.Add("onkeyup", "javascript:this.value=Comma(this.value);"); 

function Comma(Num) { 

    var period = Num.indexOf('.'); 
    if (Num.length > (period + 4)) 
    alert("too many after decimal point"); 
    if (period != -1) 
    { 
     Num += '00000'; 
     Num = Num.substr(0, (period + 4)); 
    } 

此外,上述功能是給我預期的錯誤對象。誰能幫我這個。

回答

4

使用正則表達式

summat像

pattern = /^\d{1,14)(\.{1,4}\)?$/; 

if (patten.test(yourNumber)) { 
// Hunky dory 
} 
else 
{ 
// have another bash 
} 
+1

+1雖然它應該讀取'/^\ d {1,14}(\。\ d {1,4})?$ /'。我試圖糾正它,但我認爲你應該... –

1

爲什麼不使用split()方法(下面未經測試的代碼):

function Comma(num) { 
    var s = num.split('.'); 
    if (s[0].length > 14) { 
    // Too many numbers before decimal. 
    } 
    if (s[1].length > 4) { 
    // Too many numbers after decimal. 
    } 
} 

編輯
下面將採取任何編號並返回小數點前最多14位數字d,在4位數字後,大多數(當然它實際上並不驗證輸入的是一個數字,但你得到的圖片):

function Comma(num) { 
    var s = num.split('.'); 
    var beforeDecimal = s[0];   // This is the number BEFORE the decimal. 
    var afterDecimal = '0000';  // Default value for digits after decimal 
    if (s.length > 1)     // Check that there indeed is a decimal separator. 
    afterDecimal = s[1];   // This is the number AFTER the decimal. 
    if (beforeDecimal.length > 14) { 
    // Too many numbers before decimal. 
    // Get the first 14 digits and discard the rest. 
    beforeDecimal = beforeDecimal.substring(0, 14); 
    } 
    if (afterDecimal.length > 4) { 
    // Too many numbers after decimal. 
    // Get the first 4 digits and discard the rest. 
    afterDecimal = afterDecimal.substring(0, 4); 
    } 

    // Return the new number with at most 14 digits before the decimal 
    // and at most 4 after. 
    return beforeDecimal + "." + afterDecimal; 
} 

(和往常一樣的代碼是未經測試)。

+0

我試過這個,它工作的很好,但不允許我糾正這個數字。不斷給予警報。有什麼想法嗎 ? – Janet

+0

您希望如何「更正」號碼?請記住,更正從用戶輸入中收到的號碼總是很困難,因爲您不知道預期號碼是什麼。 –

+0

好吧,一旦我點擊了警報的確定按鈕,我不能糾正這個數字...對不起,如果這是一個奇怪的問題。我是JavaScript新功能的新手。 – Janet