1

When i print a floating point like 0.0000001 in JavaScript it gives me

 1e-7

how can i avoid that and instead print it "normally" ?

jww
  • 97,681
  • 90
  • 411
  • 885
clamp
  • 33,000
  • 75
  • 203
  • 299
  • 1
    This is a possible duplicate of [How to avoid scientific notation for large numbers in javascript?](http://stackoverflow.com/questions/1685680/how-to-avoid-scientific-notation-for-large-numbers-in-javascript) – Shaded May 09 '13 at 19:21
  • http://www.mredkj.com/javascript/numberFormat.html I believe this page will help you – bengoesboom May 09 '13 at 19:21

3 Answers3

4

You can use this:

var x = 0.00000001;
var toPrint = x.toFixed(7);

This sets toPrint to a string representation of x with 7 digits to the right of the decimal point. To use this, you need to know how many digits of precision you need. You will also need to trim off any trailing 0 digits if you don't want them (say, if x was 0.04).

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
  • find out precision and trim trailing zeroes? – clamp May 09 '13 at 19:29
  • @clamp Precision is probably something you know based on the context of the number. – Aaron Dufour May 09 '13 at 19:31
  • @clamp - You cannot find the precision. The problem is that floating point values are not exact (e.g., 0.1 does not have a terminating binary expansion). You simply need to pick a precision that fits your needs. As far as trailing zeroes goes, that's pretty easy: `toPrint.replace(/(\..*?)0+$/, '$1')` will chop off trailing zeroes that follow a decimal point. – Ted Hopp May 09 '13 at 19:31
1
function noExponent(n){
    var data= String(n).split(/[eE]/);
    if(data.length== 1) return data[0]; 

    var  z= '', sign= +n<0? '-':'',
    str= data[0].replace('.', ''),
    mag= Number(data[1])+ 1;

    if(mag<0){
        z= sign + '0.';
        while(mag++) z += '0';
        return z + str.replace(/^\-/,'');
    }
    mag -= str.length;  
    while(mag--) z += '0';
    return str + z;
}
kennebec
  • 102,654
  • 32
  • 106
  • 127
  • Thanks kennebec. Actually your solution above is the only one that works for preventing a number like "0.0000001" (1e-7) to be displayed with scientific notation, since doing: "0.0000001".toFixed(7) Will still display: 1e-7 At least in Chrome – spilafis Feb 25 '14 at 19:37
0

I've got a simple solution that appears to be working.

var rx = /^([\d.]+?)e-(\d+)$/;

var floatToString = function(flt) {
  var details, num, cnt, fStr = flt.toString();
  if (rx.test(fStr)) {
    details = rx.exec(fStr);
    num = details[1];
    cnt = parseInt(details[2], 10);
    cnt += (num.replace(/\./g, "").length - 1); // Adjust for longer numbers
    return flt.toFixed(cnt);
  }
  return fStr;
};

floatToString(0.0000001); // returns "0.0000001"

EDIT Updated it to use the toFixed (didn't think about it).

EDIT 2 Updated it so it will display numbers 0.0000000123 properly instead of chopping off and showing "0.00000001".

Brandon Buck
  • 7,177
  • 2
  • 30
  • 51