Formatting Javascript Strings and Numbers to 2 Decimal Places

Ole Ersoy
Dec 2, 2021

Updated Version

There’s an updated version of this article here:

Scenario

We have a number and a string and we want to format both to 2 decimal places:

var num1: any = 213.73145;
var num2: any = '213.73145';

Approach

/**
* Round the number.
* @param num The number
* @param precision The precision
*/
export function round(num: number, precision: number = 2) {
return (Math.round(num * 100) / 100).toFixed(precision);
}
var num1: any = 213.73145;
var num2: any = '213.73145';
console.log(round(num1));
console.log(round(num2));

Demo

--

--