All-around byte unit conversion function

Source: Internet
Author: User
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




  1. Class Util {
  2. /**
  3. * 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.
  4. *
  5. * @ Param int $ size, capacity count
  6. * @ Param type $ unit, the unit of capacity count. the default value is byte.
  7. * @ Param type $ decimals: the number of digits retained after the decimal point. one digit is retained by default.
  8. * @ Param type $ targetUnit: The conversion target unit, which is automatically carried by default.
  9. * @ Return type: return the unit result that meets the requirements.
  10. */
  11. Static function fileSizeConv ($ size, $ unit = 'B', $ decimals = 1, $ targetUnit = 'auto '){
  12. $ Units = array ('B', 'KB', 'mb', 'GB', 'TB', 'petab', 'EB ');
  13. $ TheUnit = array_search (strtoupper ($ unit), $ units); // which is the initial unit?
  14. // Determine Whether automatic calculation is performed,
  15. If ($ targetUnit! = 'Auto ')
  16. $ TargetUnit = array_search (strtoupper ($ targetUnit), $ units );
  17. // Cyclic computing
  18. While ($ size> = 1024 ){
  19. $ Size/= 1024;
  20. $ TheUnit ++;
  21. If ($ theUnit = $ targetUnit) // exit the loop if it is specified!
  22. Break;
  23. }
  24. Return sprintf ("% 1 \ $. {$ decimals} f", $ size). $ units [$ theUnit];
  25. }
  26. }




  1. Echo Util: fileSizeConv (6461310554654 );
  2. Result: 5.9 TB

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.