I need to round off the decimal value to decimal places using javascript.
Ex,:
16.181 to 16.18
16.184 to 16.18
16.185 to 16.19
16.187 to 16.19
I have found some answers, but most of them do not round off 16.185 to 16.19..
I need to round off the decimal value to decimal places using javascript.
Ex,:
16.181 to 16.18
16.184 to 16.18
16.185 to 16.19
16.187 to 16.19
I have found some answers, but most of them do not round off 16.185 to 16.19..
(Math.round((16.185*Math.pow(10,2)).toFixed(1))/Math.pow(10,2)).toFixed(2);
If your value is, for example 16.199 normal round will return 16.2... but with this method youll get last 0 too, so you see 16.20! But keep in mind that the value will returned as string. If you want to use it for further operations, you have to parsefloat it :)
And now as function:
function trueRound(value, digits){
return (Math.round((value*Math.pow(10,digits)).toFixed(digits-1))/Math.pow(10,digits)).toFixed(digits);
}
Thanks @ayk for your answer, I modified your function into this :
function trueRound(value, digits){
return ((Math.round((value*Math.pow(10,digits)).toFixed(digits-1))/Math.pow(10,digits)).toFixed(digits)) * 1;
}
just add " *1 " because with yours, as you wrote, 16.2 becomes 16.20 and I don't need the zero in the back.
Use-
Decimal ds=new Decimal(##.##);
String value=ds.format(inputnumber);
This will work perfectly in my case ,hope it will work 100%
[EDIT] This code does not work for a value like 18.185, as 18.185 * Math.pow(10,2) is being evaluated to 1818.4999999999997
Math.round(<value> * Math.pow(10,<no_of_decimal_places>)) / Math.pow(10,<no_of_decimal_places>) ;
Example: 1234.5678 --> 2 decimal places --> 1234.57
Math.round(1234.5678 * Math.pow(10,2)) / Math.pow(10,2) ;
function formatNumber(myNum, numOfDec) {
var dec = Math.pow(10, numOfDec);
return Math.round(myNum * dec + 0.1) / dec;
}
The code you are using for rounding off is correct. But to get the desired result please remove the .toFixed(numOfDec) from the code.
The function:
function formatNumber(myNum, numOfDec) {
var decimal = 1
for (i = 1; i <= numOfDec; i++)
decimal = decimal * 10 //The value of decimal determines the number of decimals to be rounded off with (.5) up rule
var myFormattedNum = Math.round(myNum * decimal) / decimal
return (myFormattedNum)
}
Hope it helps you in some way :)
You COULD try a simpler function...
function roundOffTo(number, place) {
return Math.round(number * place) / place;
}
How does it work? The place can be 10, 100, 1000, 10000, and so on. The reverse will be 0.1, 0.01, 0.001, and so on. Let's say your number is 16.185, and your place is 100. The first thing it'll do is to multiply the number by the place, which is 1618.5. Rounding it off by Math.round will result in 1619. Dividing by the place gives us 16.19. There. By the way, no need to worry about the .5 problem today, it's kinda fixed. But just in case it isn't, change Math.round(number * place) to Math.round(number * place + 0.1).