Thursday, May 13, 2010

[PHP] Always show 2 decimal points

Olen päris pikalt nüüd kirjutanud igasuguseid koode ning saanud kõvasti abi välismaistelt kodeerijatelt, kes on ise seesuguseid probleeme juba läbilahendanud. Leian, et nüüd on minu aeg neile vastu pakkuda midagi.

I've been working on some kind of storage-module for my company and I've had a lot of help from all kinds of coders from around the world. Still there are some snippets that are often useful but have been left for private use.


This code is used if you want to print out a cost of something or anything else where you need to always show 2 decimal points

The input can be a float, int or even a string.
The output is a string because floats and ints tend to remove the excess zeros from the end.

I.e:
200.8903123 -> 200.89
1 -> 1.00
1,9 -> 1.00

The code itself:
function roundIt($number, $size){
    return round($number*$size)/$size;
}
   
function toZeros($number){
    $difference = roundIt(floatval($number) - intval($number),100);
    if($difference == 0)
        return intval($number).'.00';
   else{
        if(strlen($difference) == 3)    // e.g 0.1 is 3 letters
            return roundIt(floatval($number),100).'0';
        else if(strlen($difference) == 4)
            return roundIt(floatval($number),100);
    }
}
And to call out the function you simply call out the function and it does everything else for you.
toZeros(1);

I hope my efforts are worthwhile and someone is able to benefit from them!


[EDIT]
The code didn't take in account negative numbers etc.
Thus the working code looks something like this:
function toZeros($number){
    $difference = roundIt(floatval($number) - intval($number),100);
    if($difference == 0)
        return intval($number).'.00';
   else{                
        if($number < 0){ // input is negative
            if(strlen($difference) == 4) // -0.1 is 4 letters
                return roundIt(floatval($number),100).'0';
            else if(strlen($difference) == 5)
                return roundIt(floatval($number),100);
        }
        else{
            if(strlen($difference) == 3) // 0.1 is 3 letters
                return roundIt(floatval($number),100).'0';
            else if(strlen($difference) == 4)
                return roundIt(floatval($number),100);
        }
    }
}

No comments:

Post a Comment