Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Avoid 6 JavaScript Traps: Dates, Money, Coordinates

· 6 min read · Home Tech

In this article
  1. Formula
  2. Worked Example
  3. Why JavaScript Handles Dates, Money, and Coordinates Poorly
  4. Trap 1: Date Parsing and Timezone Ambiguity
  5. Trap 2: Floating-Point Arithmetic for Money
  6. Trap 3: Using toFixed() for Currency Formatting
  7. Trap 4: Mixing Degrees and Radians in Trigonometry
  8. Trap 5: Assuming Earth is Flat for Coordinates
  9. Trap 6: Ignoring the International Date Line
  10. How to Choose the Right Tools
  11. Frequently Asked Questions

This article identifies six common JavaScript pitfalls involving dates, money, and coordinates, and explains how to avoid them. You'll learn the root cause of each trap, the practical fix, and the reasoning behind it, so you can write more reliable code.

in t | Timestamp (ms) | ms | 1700000000000 | 0
in tz | Timezone offset (min) | min | -300 | 0
out local | Local time | - | t + tz * 60000 | 0
out utc | UTC time | - | t | 0

Formula

The calculator converts a Unix timestamp (milliseconds since 1970-01-01T00:00:00Z) into a local time by adding the timezone offset in minutes converted to milliseconds. The formula is:

local_time_ms = timestamp_ms + (timezone_offset_minutes × 60000)

Where:

  • timestamp_ms – milliseconds since the Unix epoch (input, ms)
  • timezone_offset_minutes – offset from UTC in minutes (input, min; e.g., -300 for UTC-5)
  • local_time_ms – the resulting timestamp adjusted for the timezone (output, ms)

The UTC time output simply echoes the original timestamp, representing the same instant in UTC.

Worked Example

Using the default values: timestamp = 1,700,000,000,000 ms and timezone offset = -300 minutes (UTC-5).

  1. Convert offset to milliseconds: -300 × 60000 = -18,000,000 ms
  2. Add to timestamp: 1,700,000,000,000 + (-18,000,000) = 1,699,982,000,000 ms
  3. The local time is 1,699,982,000,000 ms after the epoch, which corresponds to 2023-11-14 22:13:20 UTC-5.

The calculator shows this as the local time output, while the UTC output remains 1,700,000,000,000 ms.

Why JavaScript Handles Dates, Money, and Coordinates Poorly

JavaScript's built-in Date object is notoriously quirky. It stores dates as milliseconds since the Unix epoch, but its methods behave inconsistently across browsers and timezones. For example, new Date("2023-01-01") parses as UTC, while new Date("2023/01/01") parses as local time, leading to off-by-one-day errors. Similarly, floating-point arithmetic is imprecise for money (0.1 + 0.2 !== 0.3), and coordinate calculations often misuse degrees vs radians or ignore the curvature of the Earth. These pitfalls are common because JavaScript was designed for simplicity, not precision.

Trap 1: Date Parsing and Timezone Ambiguity

The biggest date trap is relying on the Date constructor to parse strings. Different formats yield different timezones, and browsers may interpret the same string differently. For instance, new Date("2023-06-01") is UTC, but new Date("2023-06-01 12:00") is local time. This causes off-by-one-day errors when the user is behind UTC.

Avoid it: Parse dates manually using Date.UTC() or a library like date-fns. Always specify the timezone explicitly when creating dates, or use ISO 8601 strings with a timezone offset (e.g., "2023-06-01T12:00:00Z").

Trap 2: Floating-Point Arithmetic for Money

JavaScript uses IEEE 754 double-precision floating-point, which cannot represent most decimal fractions exactly. For example, 0.1 + 0.2 yields 0.30000000000000004. When dealing with money, this causes rounding errors in totals, tax calculations, and comparisons.

Avoid it: Represent money as integers in the smallest unit (e.g., cents) and perform arithmetic with integers. If you must use decimals, round at the end of each operation using Math.round() with a multiplier. For example, Math.round((0.1 + 0.2) * 100) / 100 gives 0.3.

Trap 3: Using toFixed() for Currency Formatting

toFixed() rounds to a fixed number of decimal places, but it can return unexpected results due to floating-point errors. For instance, (1.005).toFixed(2) returns "1.00" instead of "1.01" because 1.005 is stored as 1.00499999999999989. This is a common trap when formatting prices.

Avoid it: Use Intl.NumberFormat with the currency style, which handles rounding correctly according to the locale. For example, new Intl.NumberFormat('en-US', {style: 'currency', currency: 'USD'}).format(1.005) returns "$1.01".

Trap 4: Mixing Degrees and Radians in Trigonometry

When calculating distances or bearings from coordinates, JavaScript's Math.sin(), Math.cos(), and Math.atan2() expect angles in radians, not degrees. A common mistake is passing degrees directly, leading to wildly incorrect results. For example, Math.sin(30) returns 0.5? No, it returns -0.988, because 30 radians is not 30 degrees.

Avoid it: Convert degrees to radians with radians = degrees * Math.PI / 180 before calling trigonometric functions. When using the Haversine formula for distance, ensure all latitude and longitude values are converted to radians.

Trap 5: Assuming Earth is Flat for Coordinates

For short distances, the Pythagorean theorem on a flat plane may suffice, but for larger distances, it fails because the Earth is a sphere. Using a simple Euclidean distance on latitude/longitude coordinates can produce errors of kilometers over just a few degrees. The Haversine formula accounts for the spherical shape and is the standard for great-circle distances.

Avoid it: Use the Haversine formula or the more accurate Vincenty formula for long distances. For short distances (under 1 km), you can use the equirectangular approximation, but always be aware of the error margin.

Trap 6: Ignoring the International Date Line

When working with dates and coordinates together, the International Date Line (180° longitude) can cause off-by-one-day errors. For example, a flight from Fiji (UTC+12) to Hawaii (UTC-10) crosses the date line, and adding or subtracting hours naively can result in a date that is one day off. Similarly, calculating the midpoint of two coordinates that straddle the date line can give a point on the opposite side of the globe.

Avoid it: When manipulating dates, always use UTC internally and convert to local time only for display. For coordinates, normalize longitudes to the range -180 to 180, and when computing midpoints, handle the wrap-around by adding 360 to negative longitudes before averaging, then subtract 360 if the result exceeds 180.

How to Choose the Right Tools

For dates, consider using date-fns or Luxon for robust parsing and timezone handling. For money, use integer arithmetic or libraries like decimal.js for arbitrary precision. For coordinates, use the Haversine formula for distances and turf.js for geospatial operations. Always prefer well-tested libraries over reinventing the wheel, but understand the underlying math to avoid misuse.

Frequently Asked Questions

Why does 0.1 + 0.2 not equal 0.3 in JavaScript?

Because JavaScript uses binary floating-point, which cannot represent 0.1 exactly. The result is a tiny rounding error. To avoid this, work with integers (cents) or use a decimal library.

Should I use new Date() or Date.now()?

Use Date.now() to get the current timestamp as a number. Use new Date() when you need a Date object for manipulation. Avoid parsing strings with new Date() unless you know the format is ISO 8601 with timezone.

What is the best way to format currency in JavaScript?

Use Intl.NumberFormat with the currency style. It handles locale-specific symbols, decimal separators, and rounding correctly. For example: new Intl.NumberFormat('de-DE', {style:'currency', currency:'EUR'}).format(1234.56).

How do I calculate distance between two coordinates accurately?

Use the Haversine formula, which gives great-circle distance. Convert degrees to radians, then apply the formula. For very high accuracy, use Vincenty's formula, but it's more complex.

Why does my date show the wrong day when I parse "2023-01-01"?

Because the ISO date-only format is parsed as UTC, so if you're in a timezone behind UTC, it may appear as the previous day. Add a timezone offset or parse the string manually.

Can I use Math.round() for money?

Yes, but only if you multiply by a factor first. For cents, do Math.round(value * 100) / 100. For large sums, consider integer arithmetic to avoid floating-point errors.