jQuery圆形进度条显示不正确的百分比。

3

我一直在使用以下的jQuery环形进度条,最近发现了一个问题。当值为0.29时,应该显示29%,但实际上显示的是28%。

https://github.com/kottenator/

$(document).ready(function($) {
 $('.progressbar').each(function () {
    var elementPos = $(this).offset().top;
    var topOfWindow = $(window).scrollTop();
    var percent = $('input[id$=hdProfitPerc]').val();  //$(this).find('.circle').attr('data-percent');
    var percentage = parseInt(percent, 10) / parseInt(100, 10);
    var animate = $(this).data('animate');
    var Profit = $('input[id$=hdProfit]').val();
    //alert($('input[id$=hdProfitPerc]').val());

    var clr

    if (percent < 0) {
        clr = 'red'
    }
    else {
        clr = 'green'
    }

    if (elementPos < topOfWindow + $(window).height() - 30 && !animate) {
        $(this).data('animate', true);
        $(this).find('.small-circle').circleProgress({
            startAngle: -Math.PI / 2,
            value: 0.29, //percentage,
            thickness: 8,
            fill: {
                color: clr
            }
        }).on('circle-animation-progress', function (event, progress, stepValue) {
            //$(this).find('div').text(String(stepValue.toFixed(2)).substr(2) + '%');
            $(this).find('div').text(parseInt(stepValue * 100) + '%');
        }).stop()
         .on('circle-animation-end', function (event) {
             $(this).find('#GP').html(Profit);
         })
    }
});

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.rawgit.com/kottenator/jquery-circle-progress/1.2.0/dist/circle-progress.js"></script>
<div id="div_progressbar" runat="server">
  <div class="progressbar" style="padding-left: 80px;">
    <div class="small-circle">
      <div></div>
      <span id="GP" style="color: black"></span>
    </div>
  </div>
</div>

如果我将值从0.29更改为0.291,则它可以正常工作。


这段代码可以正常工作 $(this).find('div').text(String(stepValue.toFixed(2)).substr(2) + '%'); 但是无法处理100%,而是显示00%。 - user1263981
1个回答

2
这是修复方法:
   $(this).find('div').text(Math.round(parseFloat(stepValue * 100)) + '%');

或者,只需使用以下代码:$(this).find('div').text(Math.round(stepValue * 100) + '%');

演示:

https://jsfiddle.net/tq4jok5r/2/

经过测试,我注意到这个特定的数字(28.999999xxxx)被舍入为较小的整数...P.S. 对于更多不同的值,测试了几个,都正常。


@user1263981,嗯...Math.round应该可以用了 :) 请检查编辑。 - sinisake
这个运行良好 :) ,我认为不需要使用 parseFloat。 - user1263981
@user1263981,尝试使用0.29和parseInt() -> 再次返回28。因此,最好使用parseFloat()。 :) - sinisake
不返回这个,只返回29 $(this).find('div').text(Math.round(stepValue * 100) + '%'); 我相信Math.round就足够了。 - user1263981
@user1263981,太好了,甚至更好-因此Math.round是解决方案,无论如何... :) - sinisake

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接