How can I parse user input decimals based on the current locale in React Native, using a dot or comma for the decimal separator?

前端 未结 1 1055
我在风中等你
我在风中等你 2020-12-22 13:19

I have a number input that pops up a \"numeric\" text input in React Native.

In many locales this brings up a numeric pad with a comma for decimal separation, inst

相关标签:
1条回答
  • 2020-12-22 13:50

    This function will parse a decimal input based on the current locale, using react-native-localize:

    import { getNumberFormatSettings } from "react-native-localize";
    
    export function parseLocaleNumber(stringNumber: string) {
      const { decimalSeparator, groupingSeparator } = getNumberFormatSettings();
    
      return Number(
        stringNumber
          .replace(new RegExp(`\\${groupingSeparator}`, "g"), "")
          .replace(new RegExp(`\\${decimalSeparator}`), "."),
      );
    }
    

    For good measure, this complementary function provides toFixed functionality based on locale:

    export function toFixedLocale(value: number, numDigits: number) {
      const standardFixedString = value.toFixed(numDigits);
    
      const { decimalSeparator } = getNumberFormatSettings();
    
      if (decimalSeparator === ",") {
        return standardFixedString.replace(".", ",");
      } else {
        return standardFixedString; // Locale matches JavaScript default
      }
    }
    

    (parseLocaleNumber based on https://stackoverflow.com/a/42213804/152711)

    0 讨论(0)
提交回复
热议问题