0 votes
in Programming by (580 points)

I want to build a rounding logic that passes the below given test cases :
Result for 0.045 :4
Result for 0.955 :96
Result for 0.995 :100
Result for 0.01 :1
Result for 0.1 :10
Result for 0.175 :18
Result for 0.007 :1
Result for 0.818 :82

Current Code :

function roundOff(num){
var ld = (num *1000)%100

if (ld >= 50){
return (Math.ceil(num*100));
}
else{ 
return (Math.floor(num*100));
}
}

document.write("Result for 0.045 :"+roundOff(0.045)+ "<br>");
document.write("Result for 0.955 :"+roundOff(0.955)+ "<br>");
document.write("Result for 0.995 :"+roundOff(0.995)+ "<br>");
document.write("Result for 0.01 :"+roundOff(0.01)+ "<br>");
document.write("Result for 0.1 :"+roundOff(0.1)+ "<br>");
document.write("Result for 0.175 :"+roundOff(0.175)+ "<br>");
document.write("Result for 0.007 :"+roundOff(0.007)+ "<br>");
document.write("Result for 0.818 :"+roundOff(0.818)+ "<br>");

Currently the last two result are not coming up as expected. I know that a different rounding is used in the last two cases. Is it possible to write a single logic that covers both ?

Please log in or register to answer this question.

...