为jQuery数字累加功能添加小数位支持
Hey there! I see the issue with your count-up script—let's get those decimal steps working properly.
The Root Problem
Your current code uses parseInt() to read the data-speed value. When you pass a decimal like 0.2, parseInt() truncates it to 0, so your counter never actually increments. That's why the script seems to fail for decimal steps!
The Fix
We'll make three key changes to support both integer and one-decimal-place steps:
- Use
parseFloat()instead ofparseInt()to correctly read decimal values. - Handle floating-point precision issues (since JavaScript can sometimes miscalculate decimals like
0.2 + 0.2 + 0.2as0.6000000000000001). - Update the number formatting function to handle decimal values while keeping comma separators for large numbers.
Modified Full Code
JavaScript
$(document).ready(function() { // Use a function reference instead of a string for better practice timer = setInterval(countUP, 1000); }); var timer; function countUP() { var elements = document.getElementsByClassName("standard"); for (var i = 0; i < elements.length; i++) { const element = elements[i]; // Parse speed as a float to support decimals const speed = parseFloat(element.getAttribute('data-speed')); // Get current counter value, default to 0 if not set let currentCounter = parseFloat(element.getAttribute('data-counter')) || 0; // Calculate new counter value let newCounter = currentCounter + speed; // Format to 1 decimal place to avoid precision errors newCounter = Number(newCounter.toFixed(1)); // Update the data attribute and display element.setAttribute('data-counter', newCounter); element.innerHTML = numberWithCommas(newCounter.toString()); } } function numberWithCommas(x) { // Split number into integer and decimal parts const parts = x.split('.'); let integerPart = parts[0]; const decimalPart = parts.length > 1 ? '.' + parts[1] : ''; // Add commas to the integer part const pattern = /(-?\d+)(\d{3})/; while (pattern.test(integerPart)) { integerPart = integerPart.replace(pattern, "$1,$2"); } return integerPart + decimalPart; }
HTML
Your existing HTML setup works fine—just make sure the data-speed attribute can hold decimals (your PHP code already handles this):
<div class="<?php echo $row["countuptype"]; ?>" data-speed="<?php echo $row["countupspeed"]; ?>">0</div>
How It Works
- Decimal Support:
parseFloat()reads values like0.2correctly instead of truncating them to0. - Precision Fix:
toFixed(1)ensures we always display exactly one decimal place, eliminating weird floating-point artifacts. - Proper Formatting: The updated
numberWithCommas()function now handles both integer and decimal values, so large numbers like1234.5will display as1,234.5.
This will work seamlessly for both integer steps (like 3) and one-decimal steps (like 0.2), giving you the behavior you want: 0.2 → 0.4 → 0.6... or 3 → 6 → 9....
内容的提问来源于stack exchange,提问作者Daniel Chapman

