covertx 0 Newbie Poster
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.
posted a minimal message; below is a concise, practical reference for JavaScript's Math.round with common pitfalls and a small utility for rounding to a fixed number of decimals.
Math.round(x) returns the numeric value x rounded to the nearest integer. Ties (fractional part exactly .5) are resolved toward +Infinity (for example, Math.round(1.5) is 2 and Math.round(-1.5) is -1). Arguments are coerced to Number; invalid conversions yield NaN. Official documentation and the ECMAScript definition are available here: MDN - Math.round and ECMAScript spec (Math.round).
Example behaviors:
Math.round(1.4); // 1
Math.round(1.5); // 2
Math.round(-1.5); // -1
Math.round(NaN); // NaN To round to a fixed number of decimal places, a common pattern is shown below; Number.EPSILON helps reduce binary floating-point surprises but is not a perfect solution for all cases:
function roundTo(num, decimals) {
var factor = Math.pow(10, decimals);
return Math.round((num + Number.EPSILON) * factor) / factor;
}
roundTo(1.005, 2); // 1.01 (expected) For financial or exact decimal requirements, integer arithmetic (cents) or a decimal library is recommended instead of relying on floating-point tricks (see decimal.js on GitHub).
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.