You are here

public static function Fraction::createFromDecimal in Fraction 8

Same name and namespace in other branches
  1. 2.x src/Fraction.php \Drupal\fraction\Fraction::createFromDecimal()

Calculates the numerator and denominator from a decimal value.

Parameters

string|int $value: The decimal value to start with.

Return value

Fraction Returns this object.

Overrides FractionInterface::createFromDecimal

8 calls to Fraction::createFromDecimal()
DecimalFraction::transform in src/Plugin/migrate/process/DecimalFraction.php
Performs the associated process.
Fraction::fromDecimal in src/Fraction.php
Calculates the numerator and denominator from a decimal value.
FractionConstraintTest::generateFraction in tests/src/Kernel/Plugin/Constraints/FractionConstraintTest.php
Helper method that generates fraction from decimal to set it on field.
FractionDecimal::validateDecimal in src/Element/FractionDecimal.php
Validates the fraction_decimal element.
FractionItem::generateSampleValue in src/Plugin/Field/FieldType/FractionItem.php
Generates placeholder field values.

... See full list

File

src/Fraction.php, line 48

Class

Fraction
A simple class for representing and acting upon a fraction.

Namespace

Drupal\fraction

Code

public static function createFromDecimal($value) {

  // Calculate the precision by counting the number of decimal places.
  $precision = strlen(substr(strrchr($value, '.'), 1));

  // Create the denominator by raising 10 to the power of the precision.
  if (function_exists('bcpow')) {
    $denominator = bcpow(10, $precision);
  }
  else {
    $denominator = pow(10, $precision);
  }

  // Calculate the numerator by multiplying the value by the denominator.
  if (function_exists('bcmul')) {
    $numerator = bcmul($value, $denominator, 0);
  }
  else {
    $numerator = $value * $denominator;
  }
  return new Fraction($numerator, $denominator);
}