Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: format number with locale #269

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)`
Expand Down
21 changes: 4 additions & 17 deletions src/decimalToSexagesimal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,35 +5,22 @@ 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));
const minFull = imprecise(Number('0.' + (post || 0)) * 60);
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;