Skip to content

Commit

Permalink
use browser locales
Browse files Browse the repository at this point in the history
  • Loading branch information
izolate committed Mar 12, 2023
1 parent c585ea3 commit 0239016
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 2 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [6.1.0] - 2023-03-11
- Defaults to browser locales from `navigator.languages`

## [6.0.2] - 2023-03-11
- Update readme

Expand Down
4 changes: 2 additions & 2 deletions lib/millify.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { defaultOptions, MillifyOptions } from "./options";
import { getFractionDigits, parseValue, roundTo } from "./utils";
import { getFractionDigits, getLocales, parseValue, roundTo } from "./utils";

// Most commonly used digit grouping base.
const DIGIT_GROUPING_BASE = 1000;
Expand Down Expand Up @@ -98,7 +98,7 @@ function millify(value: number, options?: Partial<MillifyOptions>): string {
const space = opts.space ? " " : "";

// Format the number according to the desired locale.
const formatted = rounded.toLocaleString(opts.locales, {
const formatted = rounded.toLocaleString(opts.locales ?? getLocales(), {
// toLocaleString needs the explicit fraction digits.
minimumFractionDigits: getFractionDigits(rounded),
});
Expand Down
10 changes: 10 additions & 0 deletions lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,13 @@ export function getFractionDigits(num: number): number {
const decimalPart = num.toString().split(".")[1];
return decimalPart?.length ?? 0;
}

/**
* Returns the default browser locales.
*/
export function getLocales(): string[] {
if (typeof navigator === "undefined") {
return [];
}
return Array.from(navigator.languages ?? []);
}

0 comments on commit 0239016

Please sign in to comment.