How to convert a float to a string with specific precision in JavaScript

1 Answer

0 votes
var f = new Number(341.895).toPrecision(1);
console.log(f); // 3e+2 // = 3 * 10^2 = 300

f = new Number(341.895).toPrecision(2);
console.log(f); // 3.4e+2  // 3.4 * 10^2 = 340

f = new Number(341.895).toPrecision(3);
console.log(f); // 342 

f = new Number(341.895).toPrecision(4);
console.log(f); // 341.9 

f = new Number(341.895).toPrecision(5);  
console.log(f); // 341.89 

f = new Number(341.895).toPrecision(6);  
console.log(f); // 341.895




/*
run:
 
3e+2 
3.4e+2  
342 
341.9 
341.89 
341.895
 
*/

 



answered Nov 9, 2019 by avibootz
...