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

1

3

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?

Cervin answered 21/5, 2019 at 17:49 Comment(0)
C
4

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://mcmap.net/q/411936/-does-javascript-take-local-decimal-separators-into-account)

Cervin answered 21/5, 2019 at 17:49 Comment(1)
you don't really need regex for this - replace(groupingSeparator, '') and replace(decimalSeparator, '.') should be fineQuintinquintina

© 2022 - 2024 — McMap. All rights reserved.