Created
June 21, 2019 18:54
-
-
Save lukewlms/f2d8d37207d37c3ae9dbd40893a7934a to your computer and use it in GitHub Desktop.
Parsing and reading of localized numbers with Expo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { locale } from "expo-localization"; | |
const thousandsSeparator = (1000).toLocaleString(locale)[1] === "," ? "," : "."; | |
const decimalSeparator = thousandsSeparator === "." ? "," : "."; | |
export function parseLocaleNumber(stringNumber: string) { | |
return Number( | |
stringNumber | |
.replace(new RegExp(`\\${thousandsSeparator}`, "g"), "") | |
.replace(new RegExp(`\\${decimalSeparator}`), "."), | |
); | |
} | |
export function toFixedLocale(value: number, numDigits: number) { | |
const standardFixedString = value.toFixed(numDigits); | |
return numStringToLocale(standardFixedString); | |
} | |
export function numberToLocaleString(value: number) { | |
const str = value.toString(); | |
return numStringToLocale(str); | |
} | |
function numStringToLocale(numStr: string) { | |
if (decimalSeparator === ",") { | |
return numStr.replace(".", ","); | |
} else { | |
return numStr; // Locale matches JavaScript default | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment