如何使用符号从0到数字进行计数?数字来自DB,使用自定义函数添加K,M,B使用jquery计数器向上显示动画从0到1500,但实际显示为1.5K。
当我运行counter()时,它移除K,M,B和1.5K变为1.50。我试图获得精确的1.5K,但有计数器式动画
function number_format_short( $n, $precision = 1 ) {
if ($n < 900) {
// 0 - 900
$n_format = number_format($n, $precision);
$suffix = '';
} else if ($n < 900000) {
// 0.9k-850k
$n_format = number_format($n / 1000, $precision);
$suffix = 'K';
} else if ($n < 900000000) {
// 0.9m-850m
$n_format = number_format($n / 1000000, $precision);
$suffix = 'M';
} else if ($n < 900000000000) {
// 0.9b-850b
$n_format = number_format($n / 1000000000, $precision);
$suffix = 'B';
} else {
// 0.9t+
$n_format = number_format($n / 1000000000000, $precision);
$suffix = 'T';
}
// Remove unecessary zeroes after decimal. "1.0" -> "1"; "1.00" -> "1"
// Intentionally does not affect partials, eg "1.50" -> "1.50"
if ( $precision > 0 ) {
$dotzero = '.' . str_repeat( '0', $precision );
$n_format = str_replace( $dotzero, '', $n_format );
}
return $n_format . $suffix;
}
function counter(){
$('.cnts').each(function (index) {
var size = $(this).text().split(".")[1] ? $(this).text().split(".")[1].length : 0;
$(this).prop('Counter',0).animate({
Counter: $(this).text()
}, {
duration: 1500,
easing: 'swing',
step: function (now) {
$(this).text(parseFloat(now).toFixed(size));
}
});
});
}
答案 0 :(得分:3)
你可以这样:
首先删除后缀字母(K,M,B等)并存储在变量上。并在更新文本时附加它。
$('.cnts').each(function(index) {
var letter = $(this).text().match(/\D$/)[0]; /* Store the letter on variable */
var text = $(this).text().replace(/\D$/,""); /* Remove the letter from string so that you can calculate the number of decimal correctly */
var size = text.split(".")[1] ? text.split(".")[1].length : 0;
$(this).prop('Counter', 0).animate({
Counter: text
}, {
duration: 1500,
easing: 'swing',
step: function(now) {
$(this).text(parseFloat(now).toFixed(size) + letter); /* Append the letter here. */
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="cnts">1.5K</div>