开发者

Javascript: .9 repeating not rounding to 1

开发者 https://www.devze.com 2023-02-10 17:24 出处:网络
This code usually works, converting a fractional score into a percentage with no decimal places: $(\'.correct_percent\').contents().replaceWith(((Math.round((correctCount/questionsInRound)*100)/100)

This code usually works, converting a fractional score into a percentage with no decimal places:

$('.correct_percent').contents().replaceWith(((Math.round((correctCount/questionsInRound)*100)/100) * 100) + '%');

But when I try it where questionsI开发者_开发技巧nRound is 7 and correctCount is 4, I get 56.99999999999999%. I understand that floating point numbers are not precise, but is there a way around this? I considered using the toFixed method, but that would return 56% instead of 57%, and I feel like there might be a better way.


Math.round(4/7 * 100) returns 57.


You're taking the result from Math.round, and dividing it by 100; that's not guaranteed to leave you with a round number.

Have you tried this?

$('.correct_percent').contents().replaceWith(Math.round(correctCount*100/questionsInRound) + '%');

Seems simpler, and it seems to give the correct result.


if score is the percentage then you can try

Math.floor(score*100+.5)


var percent = (correctCount / questionsInRound * 100).toFixed(0) + '%';

0

精彩评论

暂无评论...
验证码 换一张
取 消