{

Javascript How to convert number to decimal or add zero


javascript convert number to decimal example

In this blog, we will discuss several ways to add pad two zeroes to the given number or a string.

For example, if 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 difference 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 to count as input for a given number only, which returns the digits count after the 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 a number using parseInt and use the 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, which 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);  

You can check my other post on Javascript check substring exists in a String

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.