nonopolarity
nonopolarity

Reputation: 151126

In Javascript, "" + 8.1 works fine, giving "8.1", but "" + 8.0 gives "8". How to make it give "8.0"?

In Javascript (trying in Firefox 4)

"" + 8.1

gives "8.1" (a string). But

"" + 8.0

gives "8" (also a string), but is there a way to make it give "8.0" instead like it did for 8.1?

Upvotes: 0

Views: 113

Answers (4)

Florian
Florian

Reputation: 3181

Javascript has internal type convertion (called loose typing) so that it converts 8.0 to 8 by default. Javascript has no separate datatypes for float numbers and integers like other languages. It has just the type Number. You can print numbers using printf (e.g. from a jquery plugin or you can convert the Number to a string with fixed width: (8).toFixed(1) which creates a string, so you don't have to use "" + ...

Upvotes: 0

Christian
Christian

Reputation: 1892

This will work also:

8 + 0.1 + ""

Upvotes: -1

Andrei
Andrei

Reputation: 4237

Use toFixed function:

"" + (8).toFixed(1)

Upvotes: 4

Alnitak
Alnitak

Reputation: 339917

You need a proper printf style extension for Javascript if you want to show numbers with a particular precision - you can't do it with plain type coercion.

Search for "javascript printf" here and on Google - there's plenty of suitable references.

Upvotes: 1

Related Questions