From 79dff7cdda96260bb6d0ab54df653e93722ee6c1 Mon Sep 17 00:00:00 2001 From: Daniel Schuba Date: Fri, 30 Jul 2021 09:33:42 +0200 Subject: [PATCH] feat: format number with locale --- README.md | 9 +++++++-- src/decimalToSexagesimal.ts | 21 ++++----------------- 2 files changed, 11 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index f0ffb39..de88258 100644 --- a/README.md +++ b/README.md @@ -357,14 +357,19 @@ geolib.sexagesimalToDecimal(`51° 29' 46" N`); Returns the new value as decimal number. -### `decimalToSexagesimal(value)` +### `decimalToSexagesimal(value, locale?)` Converts a decimal coordinate to sexagesimal format ```js -geolib.decimalToSexagesimal(51.49611111); // -> 51° 29' 46` +geolib.decimalToSexagesimal(51.49611111); // -> 51° 29' 46"` ``` +```js +geolib.decimalToSexagesimal(51.4062305555556, 'de'); // -> 51° 24' 22,43" +``` + + Returns the new value as sexagesimal string. ### `geolib.getLatitude(point, raw = false)` diff --git a/src/decimalToSexagesimal.ts b/src/decimalToSexagesimal.ts index 0105e37..b96417c 100644 --- a/src/decimalToSexagesimal.ts +++ b/src/decimalToSexagesimal.ts @@ -5,7 +5,7 @@ const imprecise = (number: number) => { }; // Converts a decimal coordinate value to sexagesimal format -const decimal2sexagesimal = (decimal: number) => { +const decimal2sexagesimal = (decimal: number, locale?: string | string[]) => { const [pre, post] = decimal.toString().split('.'); const deg = Math.abs(Number(pre)); @@ -13,27 +13,14 @@ const decimal2sexagesimal = (decimal: number) => { const min = Math.floor(minFull); const sec = imprecise((minFull % min || 0) * 60); + const formatter = new Intl.NumberFormat(locale, {minimumIntegerDigits: 2}); + // We're limiting minutes and seconds to a maximum of 6/4 decimal places // here purely for aesthetical reasons. That results in an inaccuracy of // a few millimeters. If you're working for NASA that's possibly not // accurate enough for you. For all others that should be fine. // Feel free to create an issue on GitHub if not, please. - return ( - deg + - '° ' + - Number(min.toFixed(6)) - .toString() - .split('.') - .map((v, i) => (i === 0 ? v.padStart(2, '0') : v)) - .join('.') + - "' " + - Number(sec.toFixed(4)) - .toString() - .split('.') - .map((v, i) => (i === 0 ? v.padStart(2, '0') : v)) - .join('.') + - '"' - ); + return `${deg}° ${formatter.format(Number(min.toFixed(6)))}' ${formatter.format(Number(sec.toFixed(4)))}"`; }; export default decimal2sexagesimal;