jquery减少小数; 如何从html页面运行多个输入

在我的工作中,我需要减少小数。 以下JavaScript可以很好地减少十进制,即两位小数为1,

var mynum = 32.34; myNumber = mynum.toFixed(2); // result = 32.3 

我想从html表单同时转换多个值,例如,

  82.77, 69.30, 43.75, 33.44, 26.88, 26.83, 24.89, 24.88, 24.74, 23.07, 19.31, 17.51. 

 82.8, 69.3, 44.0, 33.4, 26.8 ...... 

我希望有一个HTML表单,它接受输入数字,并在按钮单击或自动检索相同的HTML页面中的结果。

您可以创建一个值数组并循环代码并将其写入另一个数组:

 var number_list = [ 82.77, 69.30, 43.75, 33.44, 26.88, 26.83, 24.89, 24.88, 24.74, 23.07, 19.31, 17.51]; var result = []; for(var k in number_list){ result.push(number_list[k].toFixed(1)); } // if u not use IE for dev uncomment the line below for see result in console //console.log(result); 

带有输入字段jq的表单的小例子

 $('#myid').submit(function(e){ e.preventDefault(); var number_list = eval("["+ $(".numberlist").val() +"]"); var result = []; for(var k in number_list){ // add new number to result array if(typeof number_list[k] == "number") result.push(number_list[k].toFixed(1)); //append new number to a result list: 1.55 -> 1.6 $("#result").append("
  • "+number_list[k]+" -> "+number_list[k].toFixed(1)+"
  • "); } });

    HTML

     

      在此输入写入数字中用“,”分隔。

      像:1.56,213.32423424,5.234234

      JS

       $('#formID').submit(function(){ $('.decimalMe').val().toFixed(2); }); 

      (示例)HTML

       

      因此,请提供您想要在“decimalMe”类上工作的所有输入字段(其他类名称可用)。 提交表单时(并且您可以在另一个事件上触发此事件,jQuery将在具有给定类名的所有输入上运行’toFixed’…

      更新了工作版本

      小提琴: http : //jsfiddle.net/moonspace/TA37P/1/

      HTML

         Click me 

      jQuery的

       $('#clickMe').click(function(){ $('.decimalMe').each(function(){ $(this).val( ($(this).val() * 1).toFixed(2) ); }); }); 

      基本上,这个jQuery: – 循环遍历’decimalMe’的所有实例 – 读取值($(this).val() – 将它乘以我的1以使其成为一个数字(可能有更好的方法来执行此操作… ) – ‘toFixed()’更改 – 将更改的数字弹回到它来自’$(this).val(…)的字段中

      我使用了一个按钮和“点击”事件只是因为我永远无法让表单提交在jsFiddle中正常工作。 。 。

       var x = [ 82.77, 69.30, 43.75, 33.44, 26.88, 26.83, 24.89, 24.88, 24.74, 23.07, 19.31, 17.51], y =[]; for(var i = 0; i < x.length; ++i) { y.push(x[i].toFixed(2)); } console.log(y); 

      这是一个小提琴,它在输入字段中使用表单中的目标类来完成

       //when user clicks submit button $('#submitform').click(function(){ $(this).closest('form').find('.toFixed1').each(function(){ var val = parseFloat($(this).val()); //only perform operation on an actual number if(!isNaN(val)){ //overwrite the value of the field with the reduced decimal number $(this).val(val.toFixed(1)); } }) }) 

      http://jsfiddle.net/ucu64/1/