简体   繁体   English

带小数位的 Javascript 计数器

[英]Javascript counter with decimal places

I have a jsfiddle here这里有一个 jsfiddle

It's a simple javascript function that counts up to a set number.这是一个简单的 javascript 函数,可以计数到一个设定的数字。

Is it possible to do this counting but with one decimal place as well是否可以进行此计数,但也可以保留一位小数

So it count 1.1, 1.2, 1.3 etc.所以它计数为 1.1、1.2、1.3 等。

    function startCounter(){
        $('.counter').each(function (index) {
            $(this).prop('Counter',0).animate({
                Counter: $(this).text()
            }, {
                duration: 2000,
                easing: 'swing',
                step: function (now) {
                    $(this).text(Math.ceil(now));
                }
            });
        });
    }   

    startCounter();

Update更新

Check for the size of mantissa by using .split().使用 .split() 检查尾数的大小。

var size = $(this).text().split(".")[1] ? $(this).text().split(".")[1].length : 0;

and then use that to estimate .toFixed() size like this然后用它来估计像这样的 .toFixed() 大小

$(this).text(parseFloat(now).toFixed(size));

Here is an updated demo https://jsfiddle.net/dhirajbodicherla/wmaftobx/13/这是一个更新的演示https://jsfiddle.net/dhirajbodicherla/wmaftobx/13/


Instead of Math.ceil(now) use .toFixed(1) like this而不是 Math.ceil Math.ceil(now)使用.toFixed(1)像这样

parseFloat(now).toFixed(1)

Here is the updated demo https://jsfiddle.net/wmaftobx/6/这是更新的演示https://jsfiddle.net/wmaftobx/6/

This is what I did: Replace $(this).text(Math.ceil(now)) with $(this).text(Math.ceil(now)/10) and Counter: $(this).text() by Counter: $(this).text()*10 .这就是我所做的:用 $(this) $(this).text(Math.ceil(now)/10)Counter: $(this).text()替换$(this).text(Math.ceil(now)) Counter: $(this).text()*10 It will increment by tenths.它将增加十分之一。 For each additional decimal place divide or multiply by 10.每增加一个小数位,除以或乘以 10。

change one line..换一行。。

$(this).text(Math.ceil(now));

to

$(this).text(Math.round( now * 10 ) / 10);

Here is a fiddle with the updated code这是更新代码的小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM