Reputation: 34036
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" ?
Upvotes: 1
Views: 1526
Reputation: 104800
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;
}
Upvotes: 2
Reputation: 7181
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"
.
Upvotes: 0
Reputation: 234847
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).
Upvotes: 4