Truncate a number to decimal places without rounding
Cut the decimal representation after a number of digits.
function toFixedDown({ n, digits }) { return Number(`${n}`.match(new RegExp(`^-?\\d+(?:\\.\\d{0,${digits}})?`))[0]); }
Input & expected output
Input
{
"n": 25.198726354,
"digits": 2
}Expected output
25.19The edge case
Input
{
"n": -1.999,
"digits": 1
}Expected output
-1.9Know the limits
- Works on the decimal string, so floating-point drift does not round the result up.
- Numbers that print in exponent form, such as 1e-7, are outside this contract.
The function above is the implementation used by the lab. The lab validates JSON types and caps size before execution; include equivalent validation when accepting untrusted input in your application.
Source & maintenance
Based on Truncate a number to a given number of decimal places without rounding from the original 1loc collection by Nguyen Huu Phuoc, with onelifemedia. Copyright (c) 2020 phuoc-ng. MIT licensed.
Keeps the string-matching variant and returns a number; rejects exponent notation. Original MDX retained as inert source evidence.
Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.
Keep exploring
- Clamp a number to a range — Keep a number inside an inclusive minimum and maximum.
- Round to a number of digits — Apply decimal scaling and JavaScript rounding for display-oriented values.
- Add an ordinal suffix to a number — Append st, nd, rd or th to a positive integer.