2

Possible Duplicate:
How do you round to 1 decimal place in Javascript?

My Value is 1.450 and I have to round it to 1 decimal place.

I want 1.450 = 1.5 in Javascript can any body fix this please.

Community
  • 1
  • 1
BASEER HAIDER JAFRI
  • 939
  • 1
  • 17
  • 35

4 Answers4

11

You need this:

var mynum = 1.450,
  rounded = Math.round(mynum * 10) / 10;
BenM
  • 52,573
  • 26
  • 113
  • 168
4

suppose you have

var original=28.453;

Then

var result=Math.round(original*10)/10  //returns 28.5

From http://www.javascriptkit.com/javatutors/round.shtml

You can also see How do you round to 1 decimal place in Javascript?

Community
  • 1
  • 1
MaVRoSCy
  • 17,747
  • 15
  • 82
  • 125
2

Given your fiddle, the simplest change would be:

result = sub.toFixed(1) + "M";

to:

result = Math.ceil(sub.toFixed(1)) + "M";
pete
  • 24,141
  • 4
  • 37
  • 51
2

If you use Math.round then you will get 1 for 1.01, and not 1.0.

If you use toFixed you run into rounding issues.

If you want the best of both worlds combine the two:

(Math.round(1.01 * 10) / 10).toFixed(1)

You might want to create a function for this:

function roundedToFixed(_float, _digits){
  var rounder = Math.pow(10, _digits);
  return (Math.round(_float * rounder) / rounder).toFixed(_digits);
}
Community
  • 1
  • 1
Jasper de Vries
  • 19,370
  • 6
  • 64
  • 102