JavaScript: String into number / 0 instead of NaN

I want to convert any string into a number with two decimals.  This does not work for strings that contain letters:
alert( parseFloat(555).toFixed(2) );
alert( parseFloat('123').toFixed(2) );
alert( parseFloat('xyz').toFixed(2) );

Open in new window

LVL 10
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

It seems like you want to test if a value is a number first.

var  myVar = "test";
var result = 0;
if (isNaN(myVar)===true)
//this is a number
result = parseFloat(myVar).toFixed(2);
//not a number so set to 0
result = 0.00;

Open in new window

or using shorthand if statement

var myVar = 'test';
alert( (isNaN(myVar)?0.00:parseFloat(myVar).toFixed(2) ));

Open in new window

Try this:

function fixed2(numeric) {
  return (parseFloat(numeric) || 0).toFixed(2);

Open in new window

`parseFloat()` returns a `Number` or `NaN` (and note that `typeof NaN == 'number'`). `NaN` is falsy so `|| 0` will change `NaN` values to 0. And then run `toFixed(2)` on what surely must be a number.

Note that @OriNetworks code will not convert strings to numbers which is what you seem to be asking.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.