Skip to content

Commit

Permalink
feat: format number with locale
Browse files Browse the repository at this point in the history
  • Loading branch information
DaSchTour committed Jul 30, 2021
1 parent e88635b commit e1f5d55
Showing 1 changed file with 4 additions and 17 deletions.
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;

0 comments on commit e1f5d55

Please sign in to comment.