CodingForums.com

CodingForums.com (http://www.codingforums.com/index.php)
-   Post a PHP snippet (http://www.codingforums.com/forumdisplay.php?f=41)
-   -   Class: weight (http://www.codingforums.com/showthread.php?t=210740)

Lamped 12-01-2010 09:25 AM

Class: weight
 
I have a lot of useful code sitting around, I've decided to release some of it to the public. I'll make a post once a month with a class or function that may be useful to someone.

The weight class converts between metric and imperial weights. The $weight variable can be specified in a wide variety of ways:

Quote:

1t 2 stones
8tn 4 kilograms
24 st 4 oz
You get the idea...

The default wording for toMetric and toImperial can be overridden by changing the variables like weight::$textTon.

Please note: I only develop for and test with PHP 5.3+. Earlier versions are not and will not be supported.

PHP Code:

class weight {
    const 
AS_OUNCES 'oz';
    const 
AS_POUNDS 'lb';
    const 
AS_STONE 'st';
    const 
AS_TONS 't';
    const 
AS_GRAMS 'g';
    const 
AS_KILOGRAMS 'kg';
    const 
AS_TONNES 'mt';

    
// Imperial English Preferences
    
const textTon ' ton';
    const 
textTons ' tons';
    const 
textStone 'st';
    const 
textStones 'st';
    const 
textPound 'lb';
    const 
textPounds 'lb';
    const 
textOunce 'oz';
    const 
textOunces 'oz';

    
// Metric English Preferences
    
const textTonne ' tonne';
    const 
textTonnes ' tonnes';
    const 
textKilogram 'kg';
    const 
textKilograms 'kg';
    const 
textGram 'g';
    const 
textGrams 'g';

    
/**
     * Converts a weight string into an int in grams.
     *
     * @param string $weight
     *         Weight in metric or imperial. If it's numeric, it's assumed to be
     *         $defaultType.
     * @param string $defaulType
     *         One of the weight::AS_XX constants, defines what to do with numeric
     *         weights.
     * @return int
     *         The $weight in grams.
     */
    
static public function toGrams($weight$defaultType self::AS_GRAMS) {
        
// This will be the main conversion. All other routines work off this
        
if (is_numeric($weight))
            
$weight .= $defaultType;
        if (
preg_match('/^\s*(?:([0-9]+)\s*(?:t|ton|tons))?\s*(?:([0-9]+)\s*(?:st|stone))?\s*(?:([0-9]+)\s*(?:lb|lbs|lbm|lbms|pound|pounds))?\s*(?:([0-9]+)\s*(?:oz|ounces))?\s*$/i'$weight$units) && (($units[1] != '') || ($units[2] != '') || ($units[3] != '') || ($units[4] != ''))) {
            
// Is Tons/Stone/Pounds/Ounces
            
for ($i=0;$i<5;$i++) if ($units[$i] == ''$units[$i] = 0;
            return ((
$units[1]*160*14*16) + ($units[2]*14*16) + ($units[3]*16) + $units[4]) * 28.349523125;
        } elseif (
preg_match('/^\s*(?:([0-9]+)\s*(?:mt|mts|tonn|tonnes))?\s*(?:([0-9]+)\s*(?:kg|kgs|kilo|kilos|kilogram|kilograms))?\s*(?:([0-9]+)\s*(?:g|gs|gm|gms|gram|grams))?\s*$/i'$weight$units) && (($units[1] != '') || ($units[2] != '') || ($units[3] != ''))) {
            
// Is Tonnes/Kilograms/Grams
            
for ($i=0;$i<4;$i++) if ($units[$i] == ''$units[$i] = 0;
            return ((
$units[1]*1000*1000) + ($units[2]*1000) + $units[3]);
        } else {
            return 
False;
        }
    }

    
/**
     * Converts a weight string into an Imperial string.
     *
     * @param string $weight
     *         Weight in metric or imperial. If it's numeric, it's assumed to be
     *         $defaultType.
     * @param string $defaultType
     *         One of the weight::AS_XX constants, defines what to do with numeric
     *         weights.
     * @param bool $incTon
     *         If true, includes tons in the resulting string
     * @param bool $incStone
     *         If true, includes stones in the resulting string
     * @param bool $incPound
     *         If true, includes pounds in the resulting string
     * @return string
     *         Weight formatted as "0 ton 0st 0lb 0oz"
     */
    
static public function toImperial($weight$defaultType self::AS_GRAMS$incTon True$incStone True$incPound True) {
        if ((
$ounces self::toOunces($weight$defaultType)) !== False) {
            
// Conversion
            
$tons $stone $pounds 0;
            if (
$incTon) {
                
$tons floor($ounces / (16*14*160));
                
$ounces -= $tons*(16*14*160);
            }
            if (
$incStone) {
                
$stone floor($ounces / (16*14));
                
$ounces -= $stone*(16*14);
            }
            if (
$incPound) {
                
$pounds floor($ounces 16);
                
$ounces -= $pounds*16;
            }
            
$ounces round($ounces);

            
// Compile string
            
$text trim(
                (
$tons $tons.($tons==self::textTon self::textTons).' ' '').
                (
$stone $stone.($stone==self::textStone self::textStones).' ' '').
                (
$pounds $pounds.($pounds==self::textPound self::textPounds).' ' '').
                (
$ounces $ounces.($ounces==self::textOunce self::textOunces).' ' '')
            );

            
// Check for 0 ounces
            
if ($text == '')
                return 
'0'.self::textOunces;
            return 
$text;
        }
        return 
False;
    }

    
/**
     * Converts a weight string into an Metric string.
     *
     * @param string $weight
     *         Weight in metric or imperial. If it's numeric, it's assumed to be
     *         $defaultType.
     * @param string $defaultType
     *         One of the weight::AS_XX constants, defines what to do with numeric
     *         weights.
     * @param bool $incTonne
     *         If true, includes tonnes in the resulting string
     * @param bool $incKilogram
     *         If true, includes kilograms in the resulting string
     * @return string
     *         Weight formatted as "0 tonne 0kg 0g"
     */
    
static public function toMetric($weight$defaultType self::AS_GRAMS$incTonne True$incKilogram True) {
        if ((
$grams self::toGrams($weight$defaultType)) !== False) {
            
// Conversion
            
$tonnes $kilograms 0;
            if (
$incTonne) {
                
$tonnes floor($grams / (1000*1000));
                
$grams -= $tonnes*(1000*1000);
            }
            if (
$incKilogram) {
                
$kilograms floor($grams 1000);
                
$grams -= $kilograms*1000;
            }
            
$grams round($grams);

            
// Compile string
            
$text trim(
                (
$tonnes $tonnes.($tonnes==self::textTonne self::textTonnes).' ' '').
                (
$kilograms $kilograms.($kilograms==self::textKilogram self::textKilograms).' ' '').
                (
$grams $grams.($grams==self::textGram self::textGrams).' ' '')
            );

            
// Check for 0 grams
            
if ($text == '')
                return 
'0'.self::textGrams;
            return 
$text;
        }
        return 
False;
    }

    
/**
     * Converts a weight string into an int in ounces.
     *
     * @param string $weight
     *         Weight in metric or imperial. If it's numeric, it's assumed to be
     *         $defaultType.
     * @param string $defaultType
     *         One of the weight::AS_XX constants, defines what to do with numeric
     *         weights.
     * @return int
     *         The $weight in ounces.
     */
    
static public function toOunces($weight$defaultType self::AS_GRAMS) {
        if ((
$grams self::toGrams($weight$defaultType)) !== False)
            return 
$grams 28.349523125;
        return 
False;
    }


This code is provided totally free, without warranty. No credit is required (though appreciated). You can do what you like with it.


All times are GMT +1. The time now is 12:48 AM.

Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.