Skip to content

27: Format Localized Number Ranges

Format a temperature range for US English and French. ICU provides locale-specific spacing, punctuation, and units.

  • PHP 8.6 CLI. Confirm the version with php --version.
  • The intl extension with ICU 63 or later.
  • Review the previous chapter if you’re following the series in order.

Allow about 10 minutes for the walkthrough and exercise.

A runnable intl-number-range.php example.

Run the following from the root of the Code with PHP repository.

Terminal window
php code/php-8-6/27-intl-number-range/intl-number-range.php
intl-number-range.php
<?php
declare(strict_types=1);
foreach (['en_US', 'fr_FR'] as $locale) {
$formatter = IntlNumberRangeFormatter::createFromSkeleton(
'measure-unit/temperature-celsius precision-integer',
$locale,
IntlNumberRangeFormatter::COLLAPSE_UNIT,
IntlNumberRangeFormatter::IDENTITY_FALLBACK_SINGLE_VALUE,
);
printf("%s %s\n", $locale, $formatter->format(18, 22));
}
en_US 18–22°C
fr_FR 18–22 °C

The skeleton specifies the unit and precision. The collapse setting controls when a repeated unit can appear once. The identity fallback determines the rendering when the endpoints format to the same value. Output can vary with the ICU and CLDR data shipped by your system.

Format both endpoints as 18. With IDENTITY_FALLBACK_SINGLE_VALUE the range should display a single temperature.

Continue with Read and Write ZIP Archives in Memory.