You are here

function uc_weight_format in Ubercart 8.4

Same name and namespace in other branches
  1. 5 uc_store/uc_store.module \uc_weight_format()
  2. 6.2 uc_store/uc_store.module \uc_weight_format()
  3. 7.3 uc_store/uc_store.module \uc_weight_format()

Formats a weight value for display.

Parameters

float $value: Numerical weight value.

string $unit: Weight unit. One of 'lb', 'oz', 'kg', or 'g', or NULL to use store default weight units.

string $thou: The thousands separator character. If FALSE is given, no separator is used. The default, NULL, causes the configuration variable 'weight.thousands_marker' to be used, which defaults to ','.

string $dec: The decimal separator character. If FALSE is given, confusion will abound, because it will look 100 times bigger. The default, NULL, causes the configuration variable 'weight.decimal_marker' to be used, which defaults to '.'.

Return value

string String containing formatted weight, including weight units.

8 calls to uc_weight_format()
NewShipmentForm::buildForm in shipping/uc_fulfillment/src/Form/NewShipmentForm.php
Form constructor.
OrderWeightTotal::render in uc_order/src/Plugin/views/field/OrderWeightTotal.php
Renders the field.
PackageWeight::render in shipping/uc_fulfillment/src/Plugin/views/field/PackageWeight.php
Renders the field.
ProductTest::testProductNodeForm in uc_product/tests/src/Functional/ProductTest.php
Tests product node form.
ShipmentController::viewPackage in shipping/uc_fulfillment/src/Controller/ShipmentController.php
Displays the details of a package.

... See full list

File

uc_store/uc_store.module, line 310
Contains global Ubercart functions and store administration functionality.

Code

function uc_weight_format($value, $unit = NULL, $thou = NULL, $dec = NULL) {
  $output = '';
  $config = \Drupal::config('uc_store.settings')
    ->get('weight');
  $prec = $config['precision'];
  if (is_null($unit)) {
    $unit = $config['units'];
  }
  if (is_null($thou)) {
    $thou = $config['thousands_marker'];
  }
  if (is_null($dec)) {
    $dec = $config['decimal_marker'];
  }

  // If the value is significantly less than the minimum precision, zero it.
  if ($prec > 0 && round(abs($value), $prec + 1) < pow(10, -$prec)) {
    $value = 0;
  }

  // Force the weight to a positive value and add a negative sign if necessary.
  if ($value < 0) {
    $value = abs($value);
    $output .= '-';
  }

  // Format the number, like 1234.567 => 1,234.57
  $output .= number_format($value, $prec, $dec, $thou);

  // Add the units last.
  switch ($unit) {
    case 'lb':
      return t('@value lb.', [
        '@value' => $output,
      ]);
    case 'oz':
      return t('@value oz.', [
        '@value' => $output,
      ]);
    case 'kg':
      return t('@valuekg', [
        '@value' => $output,
      ]);
    case 'g':
      return t('@valueg', [
        '@value' => $output,
      ]);
    default:
      return $value;
  }
}