Home > Mobile >  JS automatically round long numbers?
JS automatically round long numbers?

Time:08-09

I have simple array:

result = [{"egn":79090114464},{"egn":92122244001},{"egn":10005870397643185154},{"egn":10000330397652279629},{"egn":10000330397652279660},]

And when I append values from it to div element JS automatically round the numbers, so:

10005870397643185154 becomes 10005870397643186000

10000330397652279629 becomes 10000330397652280000

10000330397652279660 becomes 10000330397652280000

How to avoid that ?

JSFiddle

CodePudding user response:

All numbers in JavaScript are stored as doubles (64 bit IEEE-754), which while allowing numbers as large as 1e308 (real max is higher, i don't exactly what it is) is only precise up to Number.MAX_SAFE_INTEGER which is 253 - 1 (9007199254740991) due to how doubles work.

If you a precise integer that's larger than this, use BigInt. Note that it only performs a subset of number operations and can only be operated on by other BigInts.

You can use a BigInt literal by adding n to the end of the number.

$(document).ready(function() {
result = [{"egn":79090114464n},{"egn":92122244001n},{"egn":10005870397643185154n},{"egn":10000330397652279629n},{"egn":10000330397652279660n},]
            $("#foreigners_list").empty();
            $.each(result, function(key, data) {
                $("#foreigners_list").append("<a href='#' onClick='foreignerHrefClick(" data.egn ")' class='foreigner_egn_href'>"   data.egn   "</a><br />");
            })

})

function foreignerHrefClick(egn) {
    console.log(egn);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="foreigners_list"></div>

  • Related