2012-11-25 38 views
2

目前我在格式化小數時遇到問題。輸入中的十進制數字格式化

在文本框的模糊情況下,如果用戶輸入:

1) 1 -> this should be converted to 001.00 
2) 2.5 -> this should be converted to 002.50 
3) .5 -> this should be converted to 000.50 
4) 12.4 -> this should be converted to 012.40 

所有輸入應在離開輸入或失去焦點被轉換爲相同的格式。

+0

需要更多信息。你想要在輸入字段中進行轉換嗎?在文中?在驗證之前在服務器上?你使用jQuery或任何其他的JS框架?乾杯 –

+0

是的,它應該轉換,而在客戶端使用純Javascript.Thnks – Renji

回答

2
<input type="text" onblur="formatDecimal(this)" /> 

<script type="text/javascript"> 
    function formatDecimal(input) { 
     var val = '' + (+input.value); 
     if (val) { 
      val = val.split('\.'); 
      var out = val[0]; 
      while (out.length < 3) { 
       out = '0' + out; 
      } 
      if (val[1]) { 
       out = out + '.' + val[1] 
       if (out.length < 6) out = out + '0'; 
      } else { 
       out = out + '.00'; 
      } 
      input.value = out; 
     } else { 
      input.value = '000.00'; 
     } 
    } 
</script> 
+0

離開文本框感謝Buddy.It真正有用!!你拯救我的一天! – Renji

+0

很高興我能幫忙:) –

相關問題