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?

nonopolarity
  • 146,324
  • 131
  • 460
  • 740

4 Answers4

4

Use toFixed function:

"" + (8).toFixed(1)
Andrei
  • 4,237
  • 3
  • 25
  • 31
  • 1
    since .toFixed() returns a string anyway, you don't even need to add it to the empty string. – Spudley Apr 15 '11 at 13:09
  • If you need more digits of precision but still want to strip trailing zeros, you could do something like `(8.5).toFixed(5).replace(/(.\d+?)0*$/, "$1")` – gnarf Apr 15 '11 at 13:14
1

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.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
0

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 "" + ...

Florian
  • 3,145
  • 1
  • 27
  • 38
-1

This will work also:

8 + 0.1 + ""

Christian
  • 1,872
  • 1
  • 14
  • 14