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,895 questions

51,826 answers

573 users

How to round a float to a specific number of decimal places after the point in PHP

2 Answers

0 votes
function round_pos($n, $pos=0) {
    $pw = pow(10, $pos);
    return ($n >= 0 ? ceil($n * $pw):floor($n * $pw)) / $pw;
}

echo round_pos(12.6789001, 2) . "<br />";
echo round_pos(17.9810001, 2) ."<br />";
echo round_pos(3.14159265359, 4) . "<br />";
echo round_pos(3.14159265359, 6) . "<br />";
echo round_pos(0.9871, 4) . "<br/>";
echo round_pos(-0.9871, 4) . "<br/>";
echo round_pos(0.000011113, 2);



/*
run:

12.68
17.99
3.1416
3.141593
0.9871
-0.9871
0.01

*/

 



answered Mar 21, 2019 by avibootz
0 votes
function round_pos($n, $pos=0) {
    $pw = pow(10, $pos);
    return ($n >= 0 ? ceil($n * $pw):floor($n * $pw)) / $pw;
}

echo round(12.6789001, 2) . "<br />";
echo round(17.9810001, 2) ."<br />";
echo round(3.14159265359, 4) . "<br />";
echo round(3.14159265359, 6) . "<br />";
echo round(0.9871, 4) . "<br/>";
echo round(-0.9871, 4) . "<br/>";
echo round(0.000011113, 2);



/*
run:

12.68
17.98
3.1416
3.141593
0.9871
-0.9871
0

*/

 



answered Mar 21, 2019 by avibootz

Related questions

...