Ramil Signh Ramil Signh - 5 months ago 11
jQuery Question

How to format a number using jQuery? Ex. 119.0484 I want to format it to "9999.99"?

How to format a number using jQuery? Ex. 119.0484 I want to format it to "9999.99"?

How can I achieve this? Can you give a sample code? Thank you very much to those who can help me with this. I've tried this code. But whenever I click a radio button again the value is changing. I think the problem here is the structure of my code. But also want to know if .toFixed(2) really solved the 9999.99 format..
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>


Script

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);
}
}

Answer

Your question is not clear.

But it seems you are looking to fix the decimal points. If it is so you can use check and use toFixed method.

// 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