I have the following code. I would like to have it such that if price_result equals an integer, let\'s say 10, then I would like to add two decimal places. So 10 would be 10
Simple JavaScript, string to float:
var it_price = chief_double($("#ContentPlaceHolder1_txt_it_price").val());
function chief_double(num){
var n = parseFloat(num);
if (isNaN(n)) {
return "0";
}
else {
return parseFloat(num);
}
}
@sd Short Answer: There is no way in JS to have Number datatype value with trailing zeros after a decimal.
Long Answer: Its the property of toFixed
or toPrecision
function of JavaScript, to return the String. The reason for this is that the Number datatype cannot have value like a = 2.00, it will always remove the trailing zeros after the decimal, This is the inbuilt property of Number Datatype. So to achieve the above in JS we have 2 options
If your objective is to parse, and your input might be a literal, then you'd expect a float
and toFixed
won't provide that, so here are two simple functions to provide this:
function parseFloat2Decimals(value) {
return parseFloat(parseFloat(value).toFixed(2));
}
function parseFloat2Decimals(value,decimalPlaces) {
return parseFloat(parseFloat(value).toFixed(decimalPlaces));
}
When you use toFixed
, it always returns the value as a string. This sometimes complicates the code. To avoid that, you can make an alternative method for Number.
Number.prototype.round = function(p) {
p = p || 10;
return parseFloat( this.toFixed(p) );
};
and use:
var n = 22 / 7; // 3.142857142857143
n.round(3); // 3.143
or simply:
(22/7).round(3); // 3.143
Please use below function if you don't want to round off.
function ConvertToDecimal(num) {
num = num.toString(); //If it's not already a String
num = num.slice(0, (num.indexOf(".")) + 3); //With 3 exposing the hundredths place
alert('M : ' + Number(num)); //If you need it back as a Number
}
To return a number, add another layer of parentheses. Keeps it clean.
var twoPlacedFloat = parseFloat((10.02745).toFixed(2));