如何使用点或逗号作为小数分隔符,根据 React Native 中的当前语言环境解析用户输入的小数? [英] How can I parse user input decimals based on the current locale in React Native, using a dot or comma for the decimal separator?

查看:20
本文介绍了如何使用点或逗号作为小数分隔符,根据 React Native 中的当前语言环境解析用户输入的小数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数字输入,会在 React Native 中弹出一个数字"文本输入.

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

在许多语言环境中,这会使用逗号分隔小数点的数字键盘,而不是点.这会导致输入像100,1"而不是100.1".

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 的 Number(value) 仅适用于点小数,不适用于逗号.如何确定用户当前的格式以便正确解析输入?

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?

推荐答案

此函数将解析基于当前语言环境的十进制输入,使用 react-native-localize:

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}`), "."),
  );
}

为了更好地衡量,这个补充功能提供了基于语言环境的 toFixed 功能:

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 基于 https://stackoverflow.com/a/42213804/152711)

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

这篇关于如何使用点或逗号作为小数分隔符,根据 React Native 中的当前语言环境解析用户输入的小数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆