Search code examples
flutterdartlocalenumber-formatting

How to determine the current locale's symbol for a decimal point


How can I determine the symbol for the decimal separator? The device's current locale should be used.


Solution

  • You need to use methods of NumberFormat class, available in intl library.

    NumberFormat.decimalPattern formats a number according to specified locale.

    e.g. this is how you can get device locale and format a number.

    import 'package:intl/intl.dart' show NumberFormat;
    import 'package:intl/number_symbols_data.dart' show numberFormatSymbols;
    import 'dart:ui' as ui;
    
    String getCurrentLocale() {
      final locale = ui.window.locale;
      final joined = "${locale.languageCode}_${locale.countryCode}";
      if (numberFormatSymbols.keys.contains(joined)) {
        return joined;
      }
      return locale.languageCode;
    }
    
    // ...
    
    String dec = NumberFormat.decimalPattern(getCurrentLocale()).format(1234.567);
    print(dec); // prints 1,234.567 for `en_US` locale
    

    However, to answer your initial question - here is a function that returns either decimal separator (if found any) or empty string.

    String getDecimalSeparator(String locale) {
      return numberFormatSymbols[locale]?.DECIMAL_SEP ?? "";
    }
    
    // ...
    
    print(getDecimalSeparator(getCurrentLocale())); // prints `.` for `en_US` locale.
    

    Let me know if this helped.