0

Please look at my code:

<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Click Now</button>
<p id="PPP"></p>
<script>
function myFunction() {
    var x = 123456789987654321.987654321123456789;
    document.getElementById("PPP").innerHTML =x;
}
</script>
</body>
</html>

Why when I press the button I see 123456789987654320 and not the whole number? I want the paragraph text to be the whole number, that is 123456789987654321.987654321123456789.

I know I can cast the number to a string and then go over all the chars in the array. Do you know a simpler way?

NullUserException
  • 83,810
  • 28
  • 209
  • 234
asker22
  • 197
  • 1
  • 4
  • 14
  • 2
    No. That number is simply to precise to fit in a 64bit floating point number. A numeric variable will never be able to hold it without precision loss. – Bergi Oct 02 '14 at 19:10
  • 1
    I don't see what you mean by "*and than go over all the chars in the array*". Using a string instead of a numeric literal would just require two additional quotes in your js? – Bergi Oct 02 '14 at 19:15
  • I know I can just put the value I want as a string literal. I am trying to understand how to do so with a big number. I want to know how to show long decimal number like I can do in C# for example. – asker22 Oct 02 '14 at 19:18
  • You can't. All long numbers need to be represented as strings (or some internal composite format that is used by a high-precision/bigint library). – Bergi Oct 02 '14 at 19:23
  • So how come I can do it soo easy in C# using string format? There is no such feature in JavaScript? – asker22 Oct 02 '14 at 20:12
  • I don't know how it works in C#, maybe it has a builtin bigint library or support for arbitrary-precision arithmetics - of which JavaScript indeed has neither. – Bergi Oct 02 '14 at 21:48
  • @Bergi C# has a built-in [`decimal`](http://msdn.microsoft.com/en-us/library/364x0z75.aspx) type. – NullUserException Oct 02 '14 at 22:07
  • @NullUserException: Thanks. The number in question even seems to barely fit in that type, a few more digits and the same effect would have happened in C# :-) – Bergi Oct 02 '14 at 22:33

0 Answers0