6

How to limit the decimal place to 4 in javascript with this type of values? the e is the exponent since I am using power of ten values. toFixed() doesn't seem to work.

1.0531436913408342e-7
-5.265718456704172e-7
8.425149530726674e7
Vinoth Krishnan
  • 2,925
  • 6
  • 29
  • 34
philip
  • 1,292
  • 3
  • 24
  • 44

4 Answers4

11

Try:

   Math.round(val*10000)/10000
Mikko Ohtamaa
  • 82,057
  • 50
  • 264
  • 435
  • hahah! to bad the credit goes to mikko, if only i can check both of your answers... :) thanks for the help – philip Sep 01 '11 at 12:19
  • 1
    A cleaner way to do this would be something like: ```Math.round(val*Math.pow(10,limit))/Math.pow(10,limit)``` – JustMaier Jan 24 '14 at 06:32
5

use the force, Luke... see numObj.toExponential(n)

MDN documents a javascript method specifically for limiting the number of decimal places to show in exponential notation:
*numObj*.toExponential([*fractionDigits*])

Using your example numbers you get:
1.0531436913408342e-7.toExponential(4) // returns 1.0531e-7 -5.265718456704172e-7.toExponential(4) // returns -5.2657e-7 8.425149530726674e7.toExponential(4) // returns 8.4251e+7

Quote from MDN:

Returns a string representing a Number object in exponential notation with one digit before the decimal point, rounded to fractionDigits digits after the decimal point

Pretty handy!

Kay V
  • 3,738
  • 2
  • 20
  • 20
4

Try this method: value.toPrecision(1 + 4) for 4 decimal digits.

Delgan
  • 18,571
  • 11
  • 90
  • 141
Jiri Kriz
  • 9,192
  • 3
  • 29
  • 36
0

You can use Math.round();

Using Math.round(x) will round up or down to the nearest integer (using the classic .5 rule).

You can pass in your own criteria and have it do decimal places. The link below has examples for 1, 2, and 3 decimal places.

Here is the link

sealz
  • 5,348
  • 5
  • 40
  • 70