Jdeveloper Iphone
Jdeveloper Iphone

Reputation: 217

how to apply the toFixed() to the input value in HTML5 web app

I am working on HTML5 web app in which i get input from the user and i convert it into as comma number like 1,000 but i want that with comma it should also be converted to to fixed like 1,000.00 so how to add in this method here is my code

here is the jsfiddle demo working of my code

http://jsfiddle.net/FhZ6y/3/

here is the code

 <input type="text" id="test" onBlur="addCommas(this)">
 <input type="hidden" id="testRealValue">

 <script>
 function isNumber(n) {
 return !isNaN(parseFloat(n)) && isFinite(n);
 } 
 function addCommas(input){



nStr = input.value;
if(!isNumber(nStr))return;
document.getElementById("testRealValue").value = nStr;
var offset = nStr.length % 3;
if (offset == 0)
    input.value = nStr.substring(0, offset) + nStr.substring(offset).replace(/([0-9]{3})(?=[0-9]+)/g, "$1,");
else
    input.value = nStr.substring(0, offset) + nStr.substring(offset).replace(/([0-9]{3})/g,    ",$1");
    var a =document.getElementById('testRealValue').value;
   alert(a);
} 
</script>

Upvotes: 0

Views: 288

Answers (1)

Kenneth
Kenneth

Reputation: 28737

You should first parse the float and then apply the toFixed:

function isNumber(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}
function addCommas(input){



    nStr = input.value;
    if(!isNumber(nStr))return;
    nStr = parseFloat(nStr).toFixed(2);
    document.getElementById("testRealValue").value = nStr;
    var offset = nStr.length % 3;
    if (offset == 0)
        input.value = nStr.substring(0, offset) + nStr.substring(offset).replace(/([0-9]{3})(?=[0-9]+)/g, "$1,");
    else
        input.value = nStr.substring(0, offset) + nStr.substring(offset).replace(/([0-9]{3})/g,    ",$1");
        var a =document.getElementById('testRealValue').value;
    alert(a);


}

Of course, since you're now applying the tofixed your methods for inserting the comma are using the wrong index, and you should modify it so it insert the comma in the right place, but I'll leave that up to you

Upvotes: 1

Related Questions