function Bytes::toNumber

Same name in other branches
  1. 9 core/lib/Drupal/Component/Utility/Bytes.php \Drupal\Component\Utility\Bytes::toNumber()
  2. 11.x core/lib/Drupal/Component/Utility/Bytes.php \Drupal\Component\Utility\Bytes::toNumber()

Parses a given byte size.

Parameters

int|float|string $size: An integer, float, or string size expressed as a number of bytes with optional SI or IEC binary unit prefix (e.g. 2, 2.4, 3K, 5MB, 10G, 6GiB, 8 bytes, 9mbytes).

Return value

float The floating point value of the size in bytes.

11 calls to Bytes::toNumber()
BytesTest::testToNumber in core/tests/Drupal/Tests/Component/Utility/BytesTest.php
Tests \Drupal\Component\Utility\Bytes::toNumber().
CKEditor5ImageController::getImageUploadValidators in core/modules/ckeditor5/src/Controller/CKEditor5ImageController.php
Gets the image upload validators.
EditorImageDialog::buildForm in core/modules/editor/src/Form/EditorImageDialog.php
Environment::checkMemoryLimit in core/lib/Drupal/Component/Utility/Environment.php
Compares the memory required for an operation to the available memory.
Environment::getUploadMaxSize in core/lib/Drupal/Component/Utility/Environment.php
Determines the maximum file upload size by querying the PHP settings.

... See full list

File

core/lib/Drupal/Component/Utility/Bytes.php, line 74

Class

Bytes
Provides helper methods for byte conversions.

Namespace

Drupal\Component\Utility

Code

public static function toNumber($size) : float {
    // Remove the non-unit characters from the size.
    $unit = preg_replace('/[^bkmgtpezy]/i', '', $size);
    // Remove the non-numeric characters from the size.
    $size = preg_replace('/[^0-9\\.]/', '', $size);
    if ($unit) {
        // Find the position of the unit in the ordered string which is the power
        // of magnitude to multiply a kilobyte by.
        return round($size * pow(self::KILOBYTE, stripos('bkmgtpezy', $unit[0])));
    }
    else {
        // Ensure size is a proper number type.
        return round((double) $size);
    }
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.