Skip to content

Commit 79dff7c

Browse files
committed
feat: format number with locale
1 parent e88635b commit 79dff7c

File tree

2 files changed

+11
-19
lines changed

2 files changed

+11
-19
lines changed

README.md

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -357,14 +357,19 @@ geolib.sexagesimalToDecimal(`51° 29' 46" N`);
357357

358358
Returns the new value as decimal number.
359359

360-
### `decimalToSexagesimal(value)`
360+
### `decimalToSexagesimal(value, locale?)`
361361

362362
Converts a decimal coordinate to sexagesimal format
363363

364364
```js
365-
geolib.decimalToSexagesimal(51.49611111); // -> 51° 29' 46`
365+
geolib.decimalToSexagesimal(51.49611111); // -> 51° 29' 46"`
366366
```
367367

368+
```js
369+
geolib.decimalToSexagesimal(51.4062305555556, 'de'); // -> 51° 24' 22,43"
370+
```
371+
372+
368373
Returns the new value as sexagesimal string.
369374

370375
### `geolib.getLatitude(point, raw = false)`

src/decimalToSexagesimal.ts

Lines changed: 4 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -5,35 +5,22 @@ const imprecise = (number: number) => {
55
};
66

77
// Converts a decimal coordinate value to sexagesimal format
8-
const decimal2sexagesimal = (decimal: number) => {
8+
const decimal2sexagesimal = (decimal: number, locale?: string | string[]) => {
99
const [pre, post] = decimal.toString().split('.');
1010

1111
const deg = Math.abs(Number(pre));
1212
const minFull = imprecise(Number('0.' + (post || 0)) * 60);
1313
const min = Math.floor(minFull);
1414
const sec = imprecise((minFull % min || 0) * 60);
1515

16+
const formatter = new Intl.NumberFormat(locale, {minimumIntegerDigits: 2});
17+
1618
// We're limiting minutes and seconds to a maximum of 6/4 decimal places
1719
// here purely for aesthetical reasons. That results in an inaccuracy of
1820
// a few millimeters. If you're working for NASA that's possibly not
1921
// accurate enough for you. For all others that should be fine.
2022
// Feel free to create an issue on GitHub if not, please.
21-
return (
22-
deg +
23-
'° ' +
24-
Number(min.toFixed(6))
25-
.toString()
26-
.split('.')
27-
.map((v, i) => (i === 0 ? v.padStart(2, '0') : v))
28-
.join('.') +
29-
"' " +
30-
Number(sec.toFixed(4))
31-
.toString()
32-
.split('.')
33-
.map((v, i) => (i === 0 ? v.padStart(2, '0') : v))
34-
.join('.') +
35-
'"'
36-
);
23+
return `${deg}° ${formatter.format(Number(min.toFixed(6)))}' ${formatter.format(Number(sec.toFixed(4)))}"`;
3724
};
3825

3926
export default decimal2sexagesimal;

0 commit comments

Comments
 (0)