Home > Enterprise >  add trailing zeroes if a number is an integer in TypeScript
add trailing zeroes if a number is an integer in TypeScript

Time:03-03

i have this script that uses a Regex to format a number and show only 2 digits after the float point:

let value =9.0111;
var n = value.toString().match(/^-?\d (?:\.\d{0,2})?/)[0];
console.log(n)
//Output: 9.01

how to show two zero digits after the float point if the let value is an integer?

like 9.00 ?

is there a way to do it using only the RegEx ?

CodePudding user response:

You are probably looking for toFixed:

console.log((9.01111).toFixed(2)); // 9.01
console.log((9.01).toFixed(2));    // 9.01
console.log((9).toFixed(2));       // 9.00

toFixed docs

By the way this question does not have much to do with TypeScript. I think some better tags would be javascript/numbers/number-format etc

  • Related