如何避免toFixed四舍五入,获取浮点数指定位数小数?
Hey there, let's tackle this problem where you need to get a float's value to a specific number of decimal places without any rounding—and without converting to strings. I’ve got a straightforward mathematical solution that fits your needs perfectly.
First, let's recap the issue: the toFixed() method does two things you don't want—it rounds the number (turning your 1.1864526 into 1.19) and returns a string, which isn't suitable for your scenario.
The Core Mathematical Approach
The key is to use truncation via basic arithmetic: multiply the number by 10 raised to the number of decimal places you want, cut off the decimal part, then divide back by that same factor. Here's how to implement it cleanly:
Code Snippet
function truncateToDecimal(num, decimalPlaces) { const multiplier = 10 ** decimalPlaces; return Math.trunc(num * multiplier) / multiplier; }
Let's Test Your Example
- Start with your float:
1.1864526(we want 2 decimal places) - Multiply by
10^2 = 100:1.1864526 * 100 = 118.64526 - Use
Math.trunc()to chop off the decimal part:118 - Divide back by 100:
118 / 100 = 1.18→ exactly the result you need!
Handling Negative Numbers
Unlike Math.floor() (which would incorrectly round negative numbers down, e.g., Math.floor(-1.186 * 100) = -119), Math.trunc() simply removes the decimal part regardless of the number's sign. For example:
truncateToDecimal(-1.186, 2)returns-1.18(no unwanted rounding, just clean truncation)
Edge Case: Floating Point Precision
Occasionally, floating-point arithmetic can cause tiny inaccuracies (like 0.29 * 100 = 29.000000000000004 instead of exactly 29). If this impacts your use case, you can add a tiny epsilon value to compensate without affecting the truncation:
function truncateToDecimal(num, decimalPlaces) { const epsilon = 1e-10; // A tiny value to counteract precision errors const multiplier = 10 ** decimalPlaces; return Math.trunc((num + epsilon) * multiplier) / multiplier; }
This adjusts the number just enough to fix those tiny precision glitches without altering the actual value you want to keep.
Why This Works For Your Scenario
- No string conversion involved—everything stays purely numerical, which aligns with your requirements
- Handles both positive and negative numbers correctly
- It’s simple, efficient, and easy to integrate into your code
内容的提问来源于stack exchange,提问作者Pedro Jose Otero Rodriguez

