Wesley Skeen
Wesley Skeen

Reputation: 8285

Stop .toFixed from rounding the number

I Have the following

var dividedResult =  (893/ 200);    

var result = dividedResult.toFixed(decimalPlaces);

The divided result is

4.465 

and the result is

4.5

How do I stop the rounding in this case?

I want the result to be

4.4

Upvotes: 1

Views: 2073

Answers (2)

Prasath K
Prasath K

Reputation: 5018

Try this 4.465 * 10 = 44.65 .. parseInt(44.65) = 44/10 = 4.4

result = parseInt(result * 10)/10;

For any number of decimal places

result = parseInt(result * Math.pow(10,NumberOfDecimalPlaces))/(Math.pow(10,NumberOfDecimalPlaces));

Upvotes: 4

Greg Hornby
Greg Hornby

Reputation: 7798

Expanding on Prasath's answer, if you wanted to distinguish between rounding up and rounding down to 1 decimal place you would do

Rounding down (4.4)

result = Math.floor(result * 10)/10;

Rounding up (4.5)

result = Math.ceil(result * 10)/10;

For your case, for any number of decimal places, use

result = Math.floor(result * Math.pow(10,decimalPlaces))/Math.pow(10,decimalPlaces);

Upvotes: 1

Related Questions