let num = 231.32;
console.log( num.toPrecision() );
console.log( String(num) );
{
let numStr = "250";
console.log(Number(numStr)); console.log(Number.parseFloat(numStr));
}
There is never really a real bad method just depends on the situation you are working on.
ToPrecision() will change the original number and round to specific decimal:
Note that ToPrecision() could only deal with number and will produce error with deal with string.
The toPrecision() method returns a string representing the Number object to the specified precision
Number v.s ParseFloat is almost the same in most of the situation, but Number will return NaN and parseFloat will return the number part when deal with a string that contain some characters and number. (e.g 123ABC)
Example:
let num = '123ABC'
//return 123
console.log(parseFloat(num))
//return NaN
console.log(Number(num))
let num1='123'
//Produce error
console.log(num1.toPrecision(2))
I think the main difference between String and use " " is that you can't always and it is very annoying to redeclare the things you want (e.g. redeclare ABC to "ABC"). (I think your numStr is to show use " " change string.
Another built-in function to use is toString() to convert to string, but toString will produce error when you use want to convert null and undefined.
Example:
let test = undefined;
//produce 'undefined'
console.log(String(test))
//produce error
console.log(test.toString())
I think it is OK to use any of them in the most situation, but you have to notice the small difference. They are not totally same.