Jump to content

setAttribute troubles


qszhc123

Recommended Posts

there is a <input type="hidden" id="test1"> in my page, and i want to use JS to give it a long string consisting of numbers,which is like  "454544878545455487",

when some button(<input type="button" onclick="testFunc();">) is clicked.

The testFunc is like followings:

<script type="text/javascript">

  function testFunc()

  {

    document.getElementById("test1").setAttribute("value",somestring);

    XXXX.submit();

  }

</script>

 

when the somestring is short,such as "12345678",that's ok,

but when it is long,for example,"454544878545455487", the value appears like 4.54544878545455e+17 ,

so i add a .toString() ,

document.getElementById("test1").setAttribute("value",somestring.toString());

it is now a strange string like "454544878545455500"

approximately, but doesn't equal to "454544878545455487"...

 

VERY LATE NOW,  AND THANKS VERY MUCH ~~

Link to comment
https://forums.phpfreaks.com/topic/259925-setattribute-troubles/
Share on other sites

You're not declaring it a string like you think, it's a number. What you're seeing (4.54544878545455e+17) is scientific E notation. JavaScript does this so it can represent numbers larger than it's internally physically capable of storing. Your number exceeds that maximum, so you're loosing some bits off the end and it's being rounded.

 

You can see the cut off point here:

 

var num1 = 9007199254740992;
var num2 = 9007199254740993;

if (num1 == num2) {
    // true
}

 

If you only want a string, just define it wrapped in quotes and you won't have a problem. If you don't, things get more complicated, but I'll wait and find out before spending the time typing it up! :)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.