Saturday, March 21, 2020

Javascript example - How to convert number to decimal number or add zeroes

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.oo by adding two zeroes to the number In javascript, numeric values are represented 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 store in the form 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

This takes decimalplacescount 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 decimal number with 2 digits if the input is 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)

Convert to decimal using toLocaleString() method 

 toLocaleString() method in Number used to localize version of a given number.
locale is en or ES,
Optional configurations are minimumFractionDigits =2 which is to add number of digits after a decimal point
 It accepts English language
var value = 17;    
var decimalNumber = value.toLocaleString("en",{useGrouping: false,minimumFractionDigits: 2});

Related article