Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,885 questions

51,811 answers

573 users

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
...