function DecimalItem::generateSampleValue

Same name in other branches
  1. 9 core/lib/Drupal/Core/Field/Plugin/Field/FieldType/DecimalItem.php \Drupal\Core\Field\Plugin\Field\FieldType\DecimalItem::generateSampleValue()
  2. 8.9.x core/lib/Drupal/Core/Field/Plugin/Field/FieldType/DecimalItem.php \Drupal\Core\Field\Plugin\Field\FieldType\DecimalItem::generateSampleValue()
  3. 10 core/lib/Drupal/Core/Field/Plugin/Field/FieldType/DecimalItem.php \Drupal\Core\Field\Plugin\Field\FieldType\DecimalItem::generateSampleValue()

Overrides FieldItemBase::generateSampleValue

File

core/lib/Drupal/Core/Field/Plugin/Field/FieldType/DecimalItem.php, line 119

Class

DecimalItem
Defines the 'decimal' field type.

Namespace

Drupal\Core\Field\Plugin\Field\FieldType

Code

public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
    $settings = $field_definition->getSettings();
    $precision = $settings['precision'] ?: 10;
    $scale = $settings['scale'] ?: 2;
    // $precision - $scale is the number of digits on the left of the decimal
    // point.
    // The maximum number you can get with 3 digits is 10^3 - 1 --> 999.
    // The minimum number you can get with 3 digits is -1 * (10^3 - 1).
    $max = is_numeric($settings['max']) ? $settings['max'] : pow(10, $precision - $scale) - 1;
    $min = is_numeric($settings['min']) ? $settings['min'] : -pow(10, $precision - $scale) + 1;
    // Get the number of decimal digits for the $max
    $decimal_digits = self::getDecimalDigits($max);
    // Do the same for the min and keep the higher number of decimal digits.
    $decimal_digits = max(self::getDecimalDigits($min), $decimal_digits);
    // If $min = 1.234 and $max = 1.33 then $decimal_digits = 3
    $scale = rand($decimal_digits, $scale);
    // @see "Example #1 Calculate a random floating-point number" in
    // http://php.net/manual/function.mt-getrandmax.php
    $random_decimal = $min + mt_rand() / mt_getrandmax() * ($max - $min);
    $values['value'] = self::truncateDecimal($random_decimal, $scale);
    return $values;
}

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