GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing zetcode.com — JavaScript Floating-Point Numbers - Complete Guide JavaScript Floating-Point Numberslast modified April 1, 2025 JavaScript uses a single floating-point type based on the IEEE 754 standard, implemented as 64-bit numbers. This guide explores its properties, precision challenges, and best practices for handling numerical operations effectively. JavaScript Number OverviewThis section outlines JavaScript's sole numeric type: the 64-bit Number. It's based on IEEE 754 double-precision, offering a wide range and specific precision. Understanding its limits is key to avoiding common pitfalls in calculations. The example below shows its range and typical usage scenarios. Mastery of this type is essential for effective JavaScript programming. numberOverview.js
// Number declarations
const singleNumber = 1.2345678901234567;
const smallNumber = 5.0e-324;
const largeNumber = 1.7976931348623157e308;
console.log(`Number: ${singleNumber}`);
console.log(`Smallest positive: ${smallNumber}`);
console.log(`Largest: ${largeNumber}`);
console.log(`\nNumber.MIN_VALUE: ${Number.MIN_VALUE}`);
console.log(`Number.MAX_VALUE: ${Number.MAX_VALUE}`);
console.log(`Size in bytes: ${8}`); // Always 64-bit
// Additional example: Scientific notation
const sciNotation = 1.23e-10;
console.log(`\nScientific notation: ${sciNotation}`);
JavaScript's This uniformity simplifies coding but demands caution, as precision issues arise with decimal fractions like 0.1. Unlike languages with multiple numeric types, JavaScript's single approach is versatile yet prone to rounding errors in specific cases. Use scientific notation (e.g., 1.23e-10) for very small or large values efficiently. Precision and Rounding
Precision in JavaScript's precisionExamples.js
// Precision demonstration
const a = 0.1;
const b = 0.2;
const sum = a + b;
console.log(`0.1 + 0.2 = ${sum}`);
console.log(`0.1 + 0.2 === 0.3? ${sum === 0.3}`);
console.log(`Full precision: ${sum.toString()}`);
const value = 2.34567;
console.log(`\nRounding examples:`);
console.log(`Math.round(${value}): ${Math.round(value)}`);
console.log(`Math.floor(${value}): ${Math.floor(value)}`);
console.log(`Math.ceil(${value}): ${Math.ceil(value)}`);
console.log(`toFixed(2): ${value.toFixed(2)}`);
// Additional example: Pi rounding
const pi = 3.14159;
console.log(`\nPi to 3 digits: ${pi.toFixed(3)}`);
JavaScript's binary floating-point system struggles with decimal fractions like 0.1 + 0.2, yielding 0.30000000000000004 instead of 0.3 due to base-2 limitations. These small errors can grow in repeated calculations, making precision management vital for reliability.
Methods like Comparing Floating-Point ValuesComparing floating-point numbers in JavaScript needs special techniques due to precision issues. Direct equality checks often fail, so this section offers a robust alternative method. It also covers handling special values like NaN and Infinity. The example code clarifies these challenges with practical solutions. This knowledge prevents subtle bugs in comparison logic. numberComparison.js
function nearlyEqual(a, b, epsilon = 1e-10) {
const absA = Math.abs(a);
const absB = Math.abs(b);
const diff = Math.abs(a - b);
if (a === b) return true;
if (a === 0 || b === 0 || diff < Number.EPSILON) {
return diff < (epsilon * Number.EPSILON);
}
return diff / (absA + absB) < epsilon;
}
const x = 0.1 + 0.2;
const y = 0.3;
console.log(`Direct equality: ${x === y}`);
console.log(`NearlyEqual: ${nearlyEqual(x, y)}`);
console.log(`Difference: ${x - y}`);
const nan = NaN;
const inf = Infinity;
console.log(`\nNaN === NaN: ${nan === nan}`);
console.log(`Number.isNaN(nan): ${Number.isNaN(nan)}`);
console.log(`inf === inf: ${inf === inf}`);
// Additional example: Small number comparison
const small = 1e-15;
console.log(`\nNearlyEqual(${small}, 0): ${nearlyEqual(small, 0)}`);
Using
Special cases like Floating-Point for Financial Calculations
JavaScript's financialExamples.js
const principal = 1000.00;
const interestRate = 0.05; // 5%
const years = 10;
// Using floating-point
let futureValueFloat = principal * Math.pow(1 + interestRate, years);
console.log(`Future value (floating-point): $${futureValueFloat.toFixed(2)}`);
// Workaround with integer cents
const principalCents = 100000; // $1000.00 in cents
const futureValueCents = Math.round(principalCents * Math.pow(1 + interestRate, years));
const futureValue = futureValueCents / 100;
console.log(`Accurate future value: $${futureValue.toFixed(2)}`);
const payment = 123.456789;
console.log(`\nPayment to cents: ${payment.toFixed(2)}`);
console.log(`Payment rounded up: ${Math.ceil(payment * 100) / 100}`);
console.log(`Payment rounded down: ${Math.floor(payment * 100) / 100}`);
// Additional example: Tax calculation
const price = 19.99;
const taxRate = 0.08;
const tax = Math.round(price * taxRate * 100) / 100;
console.log(`\nTax on $${price}: $${tax}`);
JavaScript's floating-point
Rounding with Best Practices
Stick to Source ReferencesLearn more from these resources: MDN Number Documentation, MDN Math Documentation, and ECMAScript Number Type. AuthorMy name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming. |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |