Formatting Javascript Strings and Numbers to 2 Decimal Places | Task

Ole Ersoy
Jun - 09  -  1 min

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