Reputation: 3
OK, I'm a novice at this but keen so help appreciated.
I have the following script that looks at field q13 which is a value and may or may not contain two decimal places. I then use the value returned and multiply by .8 to give 80% which I want to display in field q14. This works fine but decimal places can 1, 2, 3 etc. How do I ensure that I always return 2 decimal places? Rounding is not absolutely necessary.
function parseNumber(n) // Define a new function
{
var f = parseFloat(n); // Convert to float number.
return isNaN(f) ? 0 : f; // Treat invalid input as 0;
}
$("#Field13").on("change",function() {
var x = parseNumber($("#q13 input").val());
var y = x * 0.8;
$("#q14 input").val(y);
});
Upvotes: 0
Views: 74
Reputation: 21759
use toFixed
passing a number of decimals you want to have:
function parseNumber(n) // Define a new function
{
var f = parseFloat(n); // Convert to float number.
return isNaN(f) ? 0 : f; // Treat invalid input as 0;
}
$("#Field13").on("change",function() {
var x = parseNumber($("#q13 input").val());
var y = x * 0.8;
$("#q14 input").val(y.toFixed(2));
});
Upvotes: 1
Reputation: 115212
Use toFixed()
to specify number of digits to appear after the decimal point
$("#q14 input").val(y.toFixed(2));
Upvotes: 3