All-around byte unit conversion function
Capacity unit calculation, supports defining the retention length of decimal places; defining the start and target units, or automatically carrying at 1024
- Class Util {
- /**
- * The unit of capacity is calculated. the retention length of decimals can be defined. the start and target units can be defined, or the system can be carried automatically at 1024.
- *
- * @ Param int $ size, capacity count
- * @ Param type $ unit, the unit of capacity count. the default value is byte.
- * @ Param type $ decimals: the number of digits retained after the decimal point. one digit is retained by default.
- * @ Param type $ targetUnit: The conversion target unit, which is automatically carried by default.
- * @ Return type: return the unit result that meets the requirements.
- */
- Static function fileSizeConv ($ size, $ unit = 'B', $ decimals = 1, $ targetUnit = 'auto '){
- $ Units = array ('B', 'KB', 'mb', 'GB', 'TB', 'petab', 'EB ');
- $ TheUnit = array_search (strtoupper ($ unit), $ units); // which is the initial unit?
- // Determine Whether automatic calculation is performed,
- If ($ targetUnit! = 'Auto ')
- $ TargetUnit = array_search (strtoupper ($ targetUnit), $ units );
- // Cyclic computing
- While ($ size> = 1024 ){
- $ Size/= 1024;
- $ TheUnit ++;
- If ($ theUnit = $ targetUnit) // exit the loop if it is specified!
- Break;
- }
- Return sprintf ("% 1 \ $. {$ decimals} f", $ size). $ units [$ theUnit];
- }
- }
- Echo Util: fileSizeConv (6461310554654 );
- Result: 5.9 TB
|