简体   繁体   English

在小数点Javascript之前和之后追加值

[英]Append values before and after decimal point Javascript

I have numeric fields on form were users can occasionally type a decimal value with decimal place but no values on one side. 我在表单上有数字字段,用户可以偶尔键入带小数位的十进制值,但一侧没有值。 ie the intended value to be entered can be 5 or 5.00 but occasionally a user can type .5 OR 5. so in this case if they have left out values before the decimal place, I would like to add/append the value with 0.5 or if they have left out the values after the decimal place I would like to add/append with 5.00 即输入的预期值可以是5或5.00但有时用户可以键入.5 OR 5.所以在这种情况下,如果他们在小数位之前省略了值,我想添加/附加0.5或者值如果他们遗漏了小数位后的值,我想用5.00添加/追加

.5 => 0.5 .5 => 0.5
5. => 5.00 5. => 5.00

Ideally the input value would then be updated onBlur or when user clicks/tabs away from that field or anywhere else on the page. 理想情况下,输入值将在Blur上更新,或者当用户单击/标签远离该字段或页面上的任何其他位置时。 My quick attempt at this is currently as follows (untested) 我对此的快速尝试目前如下(未经测试)

$('input').on('blur', function () {

  var currentValue = $(this).val();

  var splitNumber = currentValue.split('.');
  var beforeDecimal = splitNumber[0];
  var afterDecimal = splitNumber[1];

  if (beforeDecimal.length < 1)
  {
    //add one zero before decimal
  }

  if (afterDecimal.length < 1)
  {
    //add two zeros after decimal
  }

});

Instead you can just use a combination of parseFloat and toFixed 相反,您可以使用parseFloattoFixed的组合

parseFloat('.5') --> 0.5
parseFloat('5.') --> 5

 $('input').on('blur', function() { let value = this.value; if(!isNaN(value)) { let parsedValue = parseFloat(value); $('.output').text(parsedValue.toFixed(2)); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <input type="text" /> <span>Output: </span> <span class="output"> </span> 

Here is an example may help you: 以下示例可以帮助您:

  var myNum1 = .5; var myNum2 = 5.; function pad(num){ return num.toFixed(2); } console.log(pad(myNum1)); console.log(pad(myNum2)); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM