Javascript How to convert number to decimal or add precision zero

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 as a decimal.

In JavaScript, numeric values are stored in Number type. The number can be 12,-12,12.00, “12”. 12,-12 are integers 12.00 is a floating number. “12” is a string

Multiple ways to convert numbers to decimal in Javascript

  • use Number toFixed()
  • Use Number toLocaleString() method

NumbertoFixed()

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, 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,.

To avoid this error, First, 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));

Use toLocaleString() method

The Number toLocaleString() method returns the number in a localized version.

toLocaleString(Locales, optionalConfigurations);

locale is en or ES, Optional configurations are minimumFractionDigits=2, which tells many digits after a decimal point. Other options are useGrouping and maximumFractionDigits.

Below are code formats number as in 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