How can I parse user input decimals based on the c

2020-02-16 04:39发布

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, instead of a dot. This results in inputs like "100,1" instead of "100.1".

JavaScript's Number(value) only works with dot decimals, not commas. How can I determine the user's current format in order to properly parse the input?

1条回答
够拽才男人
2楼-- · 2020-02-16 05:39

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)

查看更多
登录 后发表回答