HarmonyOS Number & Measurement Formatting Guide for Global Apps
This technical guide explores HarmonyOS number, currency, and measurement formatting for internationalized apps, covering Intl.NumberFormat parameters, notation styles, I18NUtil unit conversion, and solutions for locale mismatches, currency errors, conversion inaccuracies, mixed-language displays, performance bottlenecks, and backend compatibility.
Number Formatting Options
The article begins by detailing the core parameters of Intl.NumberFormat used in HarmonyOS for number formatting:
minimumIntegerDigits : Pads the integer part with leading zeros to meet a minimum length (e.g., 5 digits turns 123 into 00123).
minimumFractionDigits and maximumFractionDigits : Control decimal places; e.g., setting both to 2 ensures two decimal places for currency.
minimumSignificantDigits and maximumSignificantDigits : Define significant figures; e.g., 3 to 5 significant digits formats 0.00123456 as 0.00123 and 123456.789 as 123460.
useGrouping : Enables locale-specific digit grouping (e.g., 1,000,000 in English locales).
Notation Styles
Four notation options are explained:
standard : Regular decimal representation (12345.67).
scientific : Scientific notation (1.234567E4).
engineering : Exponent multiples of three (1.234567E6).
compact : Abbreviated forms like 10K or 1M.
Compact display further splits into short (10K) and long (10 thousand).
Code Examples for Number Formatting
// Scientific notation
let numberFormat1 = new Intl.NumberFormat('zh-Hans', {notation:'scientific', maximumSignificantDigits: 3});
let formattedNumber1 = numberFormat1.format(123400);
console.log(formattedNumber1); // Output: 1.23E5
// Compact short format
let numberFormat2 = new Intl.NumberFormat('zh-Hans', {notation: 'compact', compactDisplay:'short'});
let formattedNumber2 = numberFormat2.format(123400);
console.log(formattedNumber2); // Output: 12万
// Always show sign
let numberFormat3 = new Intl.NumberFormat('zh-Hans', {signDisplay : 'always'});
let formattedNumber3 = numberFormat3.format(123400);
console.log(formattedNumber3); // Output: +123,400
// Percentage format
let numberFormat4 = new Intl.NumberFormat('zh-Hans', {style: 'percent'});
let formattedNumber4 = numberFormat4.format(0.25);
console.log(formattedNumber4); // Output: 25%Currency and Unit Formatting
Currency Options
currencySign : standard (e.g., $123.45) or accounting (negative as ($123.45)).
currencyDisplay : symbol ($), code (USD), or name (美元).
Unit Options
unitDisplay : long (hectares), short (ha), narrow (ha).
unitUsage : Context-specific formatting (e.g., area-land vs. area-land-agricult).
Currency and Unit Code Examples
// Currency with symbol
let numberFormat5 = new Intl.NumberFormat('zh-Hans', {style: 'currency', currency: 'USD'});
console.log(numberFormat5.format(123400)); // US$123,400.00
// Currency with name
let numberFormat6 = new Intl.NumberFormat('zh-Hans', {style: 'currency', currency: 'USD', currencyDisplay: 'name'});
console.log(numberFormat6.format(123400)); // 123,400.00美元
// Unit formatting
let numberFormat7 = new Intl.NumberFormat('en-GB', {style: 'unit', unit: 'hectare'});
console.log(numberFormat7.format(123400)); // 123,400 ha
// Unit with usage context (conversion may apply)
let numberFormat8 = new Intl.NumberFormat('en-GB', {style: 'unit', unit: 'hectare', unitUsage: 'xxx'});
console.log(numberFormat8.format(123400)); // 304,928.041 ac (example)Measurement Conversion with I18NUtil
HarmonyOS provides i18n.I18NUtil.unitConvert for converting between measurement systems. The standard Intl API does not support unit conversion.
import { i18n } from '@kit.LocalizationKit';
let fromUnit = {unit: 'cup', measureSystem: 'US'};
let toUnit = {unit: 'liter', measureSystem: 'SI'};
let converted = i18n.I18NUtil.unitConvert(fromUnit, toUnit, 1000, 'en-US');
console.log(converted); // 236.588 LFormatting Styles for Conversion Results
long : Full unit name (2.20462 pounds).
short : Abbreviated (2.2 lbs).
narrow : Minimal (2.2lb).
Application Scenarios
Shopping apps: Convert product weight/volume for user's locale (ounces to grams).
Health apps: Convert height/weight between imperial and metric for unified analysis.
Common Issues and Solutions
1. Number Format Not Matching Local Conventions
Problem : Digits grouping or decimal separators differ from locale expectations (e.g., comma vs. point).
Solution : Set locale-specific parameters. Example for German locale (de-DE) where comma is decimal separator:
let numberFormatForEurope = new Intl.NumberFormat('de-DE', {minimumFractionDigits: 2, useGrouping: true});
console.log(numberFormatForEurope.format(12345.67)); // 12.345,67Test across locales with simulated or real data.
2. Currency Symbol Display Errors
Problem : Wrong symbol or accounting format not matching local standards.
Solution : Use correct currency code and currencyDisplay. For CNY in Chinese locale:
let numberFormatForCNY = new Intl.NumberFormat('zh-Hans', {style: 'currency', currency: 'CNY', currencyDisplay:'symbol'});
console.log(numberFormatForCNY.format(12345.67)); // ¥12345.67Follow local accounting regulations for financial apps.
3. Inaccurate Measurement Conversion
Problem : Conversion results deviate from standard values due to formula errors or unsupported units.
Solution : Verify conversion rules against international standards. For temperature, use the provided API:
function celsiusToFahrenheit(celsius) {
return i18n.I18NUtil.unitConvert(
{unit: 'Celsius', measureSystem: 'SI'},
{unit: 'Fahrenheit', measureSystem: 'SI'},
celsius, 'en-US', 'long'
);
}
console.log(celsiusToFahrenheit(25)); // 77 FahrenheitFor unsupported conversions, implement custom logic or use third-party libraries with compatibility checks.
4. Mixed-Language Environment Display Issues
Problem : Numbers formatted inconsistently within a single multilingual UI string.
Solution : Format numbers per language segment using respective locales:
let number = 12345.67;
let chineseFormat = new Intl.NumberFormat('zh-Hans');
let englishFormat = new Intl.NumberFormat('en-US');
let formattedCN = chineseFormat.format(number); // 12,345.67
let formattedEN = englishFormat.format(number); // 12,345.67
// Replace placeholders in mixed string accordingly5. Performance Optimization
Problem : Frequent formatting in lists or real-time updates causes bottlenecks.
Solution : Cache Intl.NumberFormat instances and reuse them. Precompute and cache common conversions. Avoid repeated object creation and heavy string concatenation.
let cachedNumberFormat = null;
function formatNumber(number) {
if (!cachedNumberFormat) {
cachedNumberFormat = new Intl.NumberFormat('zh-Hans');
}
return cachedNumberFormat.format(number);
}6. Backend Data Compatibility
Problem : Backend returns raw numbers or different units, mismatching frontend formatting needs.
Solution : Establish a shared format spec. If backend cannot change, transform on frontend:
function formatBackendNumber(backendNumber) {
let number = parseFloat(backendNumber);
let fmt = new Intl.NumberFormat('en-US');
return fmt.format(number);
}Maintain a unit mapping table for backend-to-frontend unit conversions.
7. Low-Configuration Device Constraints
Problem : Complex formatting overloads limited CPU/memory, causing lag or crashes.
Solution : Simplify formatting (fewer decimals, avoid scientific/compact notation). Detect device capabilities and switch to low-overhead modes. Offload formatting to background threads with proper async handling.
Conclusion
By addressing these areas — parameter configuration, notation selection, currency/unit handling, measurement conversion, locale-aware formatting, performance caching, backend alignment, and device adaptation — developers can deliver accurate, user-friendly, and efficient number and measurement displays in HarmonyOS internationalized applications. Rigorous testing and continuous optimization are essential.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
HarmonyOS Developer Technology
HarmonyOS developers provide key technology analysis, version updates, Codelabs practice, and event information for HarmonyOS. Welcome developers to join the HarmonyOS ecosystem and create infinite possibilities together!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
