问题描述
我有一个数字输入,它会在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
}
}
(基于 https://stackoverflow.com/a/42213804/152711 的parseLocaleNumber)
(parseLocaleNumber based on https://stackoverflow.com/a/42213804/152711)
这篇关于如何在React Native中基于当前语言环境使用小数点分隔符使用点或逗号来解析用户输入的小数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!