2016-06-13 18 views
-2

如何使用jQuery格式化数字?防爆。 119.0484我想将它格式化为“9999.99”?如何使用jQuery格式化数字?防爆。 119.0484我想将它格式化为“9999.99”?

我该如何做到这一点?你能给一个示例代码吗?非常感谢那些能够帮助我的人。我试过这段代码。但是每当我再次单击一个单选按钮时,数值都在变化。我认为这里的问题是我的代码结构。但也想知道,如果.toFixed(2)确实解决了9999.99格式.. HTML

<input type="radio" name="unitScale" id="opt1" onclick="changeUnit()" checked class="roleAuthorization"><label>Metric (Kg&Cm)</label> 
    <input type="radio" name="unitScale" id="opt2" onclick="changeUnit()" class="roleAuthorization"><label>English (Lbs&In)</label> 

脚本

function changeUnit() { 
    var requestNum = $("#requestNum").val(); 
    var username = $("#username").val(); 
    if ($("#opt1").is(":checked")) { 
     $("#kg").removeAttr("style"); 
     $("#lbs").attr("style", "display:none;"); 
     $("#cmtrs").removeAttr("style"); 
     $("#inches").attr("style", "display:none;"); 
     convertToMetric();  
    } else if ($("#opt2").is(":checked")) { 
     $("#kg").attr("style", "display:none;"); 
     $("#lbs").removeAttr("style"); 
     $("#cmtrs").attr("style", "display:none;"); 
     $("#inches").removeAttr("style"); 
     convertToEnglish();  
    } 
} 

function convertToMetric(){ 
    var weight = $("#weight").val(); 
    var height = $("#height").val(); 
    if ((weight != "")&&(height != "")){ 
     weight = weight/2.2046; 
     weight = weight.toFixed(2); 
     height = height/0.39370; 
     height = height.toFixed(2); 
     $("#weight").val(weight); 
     $("#height").val(height); 
    } 
} 

function convertToEnglish(){ 
    var weight = $("#weight").val(); 
    var height = $("#height").val(); 
    if ((weight != "")&&(height != "")){ 
     weight = weight/2.2046; 
     weight = weight.toFixed(2); 
     height = height/0.39370; 
     height = height.toFixed(2); 
     $("#weight").val(weight); 
     $("#height").val(height); 
    } 
} 
+0

如果你的意思是要显示两位小数的数字,使用['.toFixed()'](https://developer.mozilla.org/en-US/文档/网络/的JavaScript /参考/ Global_Objects /数字/ toFixed)。 – nnnnnn

+0

问题确实显示出严重缺乏研究工作。这个主题不难在网上搜索。请在询问之前尝试搜索 – charlietfl

+0

如果我检查英文单选按钮,我正在创建一个简单的应用程序,可将Kg转换为Lbs。防爆。我输入的56公斤将被转换为123.459,要求将其格式化为9999.99格式。 – Ishkar

回答

0

你的问题不明确。

但似乎你正在寻找修复小数点。如果是这样,你可以检查并使用toFixed方法。

// With rounding 
var x = 119.0484; 
document.write('<pre>'+x.toFixed(2)+'</pre>') 


// Without rounding 
var val = (Math.floor(100 * x)/100).toFixed(2); 
document.write('<pre>'+val+'</pre>') 

JSFIDDLE

相关问题