floor trunc And ceil Diverge On Negatives
floor, trunc and ceil agree on positives but split directions on negatives, and Math.round ties go toward positive infinity, so bucket math must pick one.
Code
// The three rounding functions agree on positives and diverge on negatives: floor toward -Infinity, trunc toward 0, ceil toward +Infinity
const values = [2.7, -2.7, 2.3, -2.3];
for (const v of values) {
console.log(
v,
'| floor', Math.floor(v),
'| trunc', Math.trunc(v),
'| ceil', Math.ceil(v),
);
}
// round rounds .5 toward +Infinity: -2.5 becomes -2 not -3, and -0.5 lands on -0
console.log('round(-2.5) =', Math.round(-2.5), '| round(2.5) =', Math.round(2.5));
console.log('round(-0.5) =', Math.round(-0.5), '| floor(-0.5) =', Math.floor(-0.5));
// trunc chops the fraction off, same for both signs - for "drop the decimals" rather than "round down"
console.log('trunc(-2.9) =', Math.trunc(-2.9), '| trunc(2.9) =', Math.trunc(2.9));
// Decide the direction before bucketing/indexing: whether -0.2 lands in bucket 0 or -1 changes membership
console.log('floor(-0.2) =', Math.floor(-0.2), '| trunc(-0.2) =', Math.trunc(-0.2));Output
Captured from a sandboxed run of this snippet in the build pipeline.
2.7 | floor 2 | trunc 2 | ceil 3
-2.7 | floor -3 | trunc -2 | ceil -2
2.3 | floor 2 | trunc 2 | ceil 3
-2.3 | floor -3 | trunc -2 | ceil -2
round(-2.5) = -2 | round(2.5) = 3
round(-0.5) = -0 | floor(-0.5) = -1
trunc(-2.9) = -2 | trunc(2.9) = 2
floor(-0.2) = -1 | trunc(-0.2) = -0Inside the snippet
Iteration happens inside for (const v of values) — everything outside it runs once.
Module-level bindings hold the data — values — with no function scope in between.
Putting it to use
Running the file prints labeled results such as round(-2.5) =, round(-0.5) =, trunc(-2.9) = — each operation’s effect is visible in the output.
Core lines
const values = [2.7, -2.7, 2.3, -2.3];
Interactive Tools for This Topic
GCD & LCM CalculatorFind the greatest common divisor and least common multiple of two or more integers, computed exactly with BigInt.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Vector Similarity CalculatorCompute Cosine Similarity, Dot Product, Euclidean L2, Manhattan L1, and Chebyshev distances between numeric vectors with dimension checks.
FAQ
- Is a package install part of the setup?
- No. Installation is unnecessary because only built-in APIs are used. Its state lives in module-level bindings: `values`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.