peterolson / BigInteger.js

An arbitrary length integer library for Javascript
The Unlicense
1.12k stars 187 forks source link

How convert bigint to string? #196

Closed behnammodi closed 4 years ago

behnammodi commented 4 years ago

bigInteger(123456789012345678).toString()

Result:

123456789012345680

Happypig375 commented 4 years ago

JavaScript number precision issues. Use bigInteger('123456789012345678').toString().

behnammodi commented 4 years ago

@Happypig375 Thank's, but this is a sample and i received that from server

bigInteger(num).toString() // result 123456789012345680

So, I can't convert to string that because this issue stay:

bigInteger(String(num)).toString() //result 123456789012345680
Happypig375 commented 4 years ago

You are using native JavaScript numbers.

String(num) // 123456789012345680
123456789012345678 == 123456789012345680 // true
behnammodi commented 4 years ago

@Happypig375 All right, but I need it.

function mask(number){
   ...
}

const number // number variable is 123456789012345678 get from server
const maskedNumber = mask(number);
// result is '123-45-6789-012345680'

But, I need this result '123-45-6789-012345678'

Yaffle commented 4 years ago

@uxitten , get the string from the server

behnammodi commented 4 years ago

Suppose I can't. No way?

Yaffle commented 4 years ago

@uxitten , a lot of ways: 1) you know, that the value can be stored as binary64 exactly, and so the conversion back to decimal is exact, in this case use number.toFixed(0); 2) parse the output from the server in a way, that the value will not be converted to number (don't call JSON.parse(...) directly)

Yaffle commented 4 years ago

Why can't you get it as string from the server? Cannot you modify the receiving code?

behnammodi commented 4 years ago

Thanks, man, it's ok