2017-10-26 1 views
0

Ich habe ein Format erstellt, das zwei Nachkommastellen zulässt, zum Beispiel 99.99 oder 55.55 usw. Ich möchte es zulassen lassen 99.999 anstelle von zwei. Nicht sicher, wo das Problem liegt.Format-Nummer erlaubt drei Ziffern Dezimalstellen statt zwei

function formatNumber (nStr) { 
    nStr = String(nStr) 
    nStr = nStr.replace(/\,/g, '') 
    nStr = trimNumber(nStr) 

    if ($.isNumeric(nStr)) { 
     nStr = String(parseFloat(nStr).toFixed(2)) 
     nStr += '' 
     x = nStr.split('.') 
     x1 = x[0] 
     if (x.length > 1) { 
      if (x[1].length > 2) { 
       var thirddigit = x[1].substr(2, 1) 
       var addone = false 
       if (Number(thirddigit) >= 5) { 
        addone = true 
       } 

       x[1] = x[1].substr(0, 2) 
       if (addone) { 
        var y = Number(x[1]) + 1 
        x[1] = y 
       } 
      } 
     } 
     x2 = x.length > 1 ? '.' + x[1] : '' 
     var rgx = /(\d+)(\d{3})/ 
     while (rgx.test(x1)) { 
      x1 = x1.replace(rgx, '$1' + ',' + '$2') 
     } 

     if (x.length > 1) { 
      if (x[1].length == 1) { 
       x2 = '.' + x[1] + '0' 
      } 
      if (x[1].length == 0) { 
       x2 = '.00' 
      } 
     } else { 
      if (x1 != '') { 
       x2 = '.00' 
      } 
     } 

     if (getLeft(x1 + x2, 1) == '.') { 
      return '0' + x1 + x2 
     } else { 
      return x1 + x2 
     } 
    } else { 
     return '' 
    } 
} 
+4

Ihr Code ist so sehr überkompensiert. Kannst du in ein paar Sätzen beschreiben, was deine Funktion machen soll? Ich bin mir ziemlich sicher, dass ich Ihnen eine Lösung in ein oder zwei Zeilen zeigen kann, die das Gleiche tut. || BTT: 'toFixed (2)' muss in '.toFixed (3)' geändert werden. Aber nochmal: Der Code ist ... ... nicht gut. –

+0

Es ist sehr schwierig, den Code zu verstehen. Bitte überprüfen Sie https://stackoverflow.com/questions/6134039/format-number-to-always-show-2-decimal-places – Telavian

Antwort

0
function Format3DigitDecimal(e, thisobj, min, max) 
    { 
     var keyCode = e.keyCode == 0 ? e.charCode : e.keyCode 
     var ret = ((keyCode >= 48 && keyCode <= 57) || (keyCode == 44) || (specialKeys.indexOf(e.keyCode) != -1 && e.charCode != e.keyCode)) 

     var inStr = $(thisobj).val() 




     if (ret && (inStr != '' && (keyCode >= 48 && keyCode <= 57))) 
     { 
      if ((inStr.length >= max.toString().length) && ((thisobj.selectionStart - thisobj.selectionEnd) == 0)) 
      { 
       ret = false 
      } 
     } 

     if (ret && (inStr != '' && (keyCode >= 48 && keyCode <= 57))) 
     { 
      if ((inStr.length == 3) && ((thisobj.selectionStart - thisobj.selectionEnd) == 0)) 
      { 
       ret = false 
      } 
     } 

     return ret 
    } 

fand ich die Lösung! Ich habe es gepostet für den Fall, dass jemand das gleiche Szenario haben würde und es braucht.

Verwandte Themen