Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mvnobrega's avatar

Format numbers with scientific notation

I receive numbers in scientific notation formats. Then I create trailing zeros with toFixed(), but it converts the return to a string, but I need them as a number. If I use Number(), it reverts to scientific notation.

Look:

if (dataPoint[1].toString().includes('e')) {
var casas = dataPoint[1].toFixed(16).split(".")[1].match(/^[0]+([1-9])/)[0].length;	
yValue = parseFloat(dataPoint[1]).toFixed(casas);
				    } else {
				      yValue = dataPoint[1];
				    }				      

How do I get decimals in number format using toFixed()?

0 likes
7 replies
mvnobrega's avatar

@jlrdw I ended up getting a little more confused... all options convert to string. I couldn't solve my problem with your help

martinbean's avatar

How do I get decimals in number format using toFixed()?

@mvnobrega I think you’re misunderstanding numbers and strings.

If you have this value:

var value = 1000.5;

And then call toFixed(2) on it then yes, it’s going to return a string, with that many numbers after the decimal point. The MDN docs do say this in the documented return type for the toFixed method: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed#return_value

The reason being, any trailing zeroes on a number are just superfluous in floating point numbers. 1000.500 is the same as 1000.5. You can test and verify this with the following code:

var value = 1000.500;
console.log(value); // 1000.5
1 like
mvnobrega's avatar

@martinbean but I receive this as a value: 1.38e-11 , it appears as a number type and I need to treat it as a number even after toFixed(). It seems so simple, but I can't solve it

martinbean's avatar

@mvnobrega Please re-read my post. I described in detail. The toFixed method returns a string. Not a number.

1 like

Please or to participate in this conversation.