I already know about the function toExponential
, which convert a number to a scientific notation. But I am wondering if another built-in function exists, that formats a number if it is too big or too small (in other words, if the number of digits is too much) . For instance, this function takes 2 arguments: a number, and a length. If the number length is higher than the length, the number is formated, otherwise, it is not.
func(12,2) // Should print 12, because the length of 12 is not bigger than 2
func(12,1) // Should print 1.2e1, because the length of 12 is bigger than 1
func(0.012,2) // Should print 1.2e-2 since the length of 0.012 is bigger than 2
This function should look like this aproximately:
const formatNumber = (num:number,digits:number):number =>{
const length = num.toString().length
return length>digits? num.toExponential(1): num
}
But I am not able to find such a function. Does it exist? If not, then I can still continue to use the one that I created, but I was just wondering if there is a more “official” function for doing this.