Quick Question

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
imatrox05
Forum Newbie
Posts: 16
Joined: Wed Mar 29, 2006 8:44 pm

Quick Question

Post by imatrox05 »

I am rounding values to 4 digits

using round($num,4) so i get values like
7.456822 to 7.4568 And sometimes i get values like 2.3 or 6 i want to fill the rest with zeros so they look like this

2.3000
6.0000

How do i get this?

Thanks in advance
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

strpos() to see if it has a decimal, str_pad() to add zeros.
imatrox05
Forum Newbie
Posts: 16
Joined: Wed Mar 29, 2006 8:44 pm

Post by imatrox05 »

Thanks for the tip but that doesnt seem to work. I am getting 1000 for all my results
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Post by Benjamin »

This should work for you...

Code: Select all

<?php

$num = 6.2;

switch ($num) {
    case is_integer($num):
        $num .= '.';
        $num = str_pad($num, 6, '0');
        break;
    case is_float($num):
        $num = str_pad($num, 6, '0');
        break;
    default:
        $num = 'Error!';
}

echo $num;


?>
AngryPanda
Forum Newbie
Posts: 16
Joined: Wed Jul 19, 2006 12:18 am

Post by AngryPanda »

That does typecast to string though. Whether or not that is an issue I do not know.

Perhaps number_format() would be a better solution for this.

Code: Select all

$num = 6.45998445;
$rounded = round($num, 4);
$formatted = number_format($rounded, 4);
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Post by Benjamin »

Yeah that would work better..
User avatar
patrikG
DevNet Master
Posts: 4235
Joined: Thu Aug 15, 2002 5:53 am
Location: Sussex, UK

Post by patrikG »

use http://php.net/sprintf in combination with (float) to typecast it.
Post Reply