In this blog, we will discuss several ways to add pad two zeroes to the given number or a string.
For example, We have a number=12, we have to output the number to 12.00 by adding two zeroes to the number.
In javascript, numeric values represent in Number type.
The number can be 12,-12,12.00. There is no differentiate between integers (12,-12)and floating numbers (12.00).
The number can also be stored in the form of strings(“12”)
Convert to a decimal using with toFixed(2) method.
Number.toFixed() method used to format the given number, outputs floating-point number. here is syntax
Number.toFixed(decimalplacescount)
This takes decimal places count as input for a given number only, which returns the digits count after decimal point(.)
In the below example The given number is converted to a decimal number with 2 digits if the input is a string, it throws TypeError:strValue.toFixed is not a function, convert the string to number using parseInt and use toFixed method
let value=12;
console.log(typeof value); //number
console.log(value.toFixed(2)); //12.00
let strValue="34";
console.log(typeof strValue); //string
console.log(strValue.toFixed(2)); //TypeError:strValue.toFixed is not a function
let num=Number.parseInt(strValue)
console.log(num.toFixed(2));
Convert to decimal using toLocaleString() method
toLocaleString() method in Number gives a localized version of a given number.
toLocaleString(Locales,optionalConfigurations)
locale is en or ES,
Optional configurations are minimumFractionDigits =2, tells many digits after a decimal point.
It accepts the English language.
var value = 17;
var decimalNumber = value.toLocaleString("en",{useGrouping: false,minimumFractionDigits: 2});
console.log(decimalNumber);