Bitcoin value as int64_t or as double

1

I want to do program that doing some calculations with bitcoin values.

I know bitcoin have 8 digits after decimal point (please correct me).

If I store the value as double I worry that I might lose precision when I do the calculations.

Shall I use int64_t instead? It generally can store 18 digit number, so if I multiply by 100,000,000, I will be able to work in satoshi units and never lose precision.

After that I will need to divide by 100,000,000 so I can print it.

And what about gcc quadruple precision?

Or shall I use GNU MP library instead?

Nick

Posted 2019-08-09T08:52:06.943

Reputation: 191

2You can use the same type of bitcoin-core for store the value of the satoshi, so int64_t. The number is always int, I think you can use the long type because also the bitcoin core RPC framework response use the conversion in Bitcoin and the wrapper libraries used the long typevincenzopalazzo 2019-08-09T09:17:21.373

Answers

0

You can use the same type of bitcoin-core for store the value of the satoshi, so int64_t. The number is always int, I think you can use the type long because also the RPC framework response use the conversion in Bitcoin and the wrapper libraries used the type long

vincenzopalazzo

Posted 2019-08-09T08:52:06.943

Reputation: 572

1Can you explain your remark about long further? On some systems, long is a 32-bit type, so I don't see how it could be safe to use it for a number of satoshis.Nate Eldredge 2019-08-09T15:05:40.950

4

I want to do program that doing some calculations with bitcoin values.

I know bitcoin have 8 digits after decimal point (please correct me).

There is no decimal in bitcoin at code level. There is no "bitcoin" unit either. There is only satoshi. And it is best to always stick to integer types instead of floating point types for calculations.

Shall I use int64_t instead? It generally can store 18 digit number, so if I multiply by 100,000,000, I will be able to work in satoshi units and never lose precision.

The number of digits doesn't matter, the size of the number in binary matters.
Since the maximum value you can have as "amount" for bitcoin is 2100000000000000 (21 million bitcoin or 21 million * 10^8 satoshi) and this value is 7 bytes (0x0775f05a074000), you need an 8 byte (64 bit) integer. So your options are a signed or unsigned 64-bit integer value type. The sign doesn't matter because the most significant bit is never set due to the size of the max value.

By the way a 64-bit signed integer has a max value of 9,223,372,036,854,775,807 which is 19 digits.

Coding Enthusiast

Posted 2019-08-09T08:52:06.943

Reputation: 488

2Note that while this is generally sane advice, there are scenarios where you will exceed 21,000,000 BTC - for example, summing up the total transaction volume in a given time period. Choosing your data type should consider whether these scenarios are possible prior to writing any code.Raghav Sood 2019-08-11T05:37:11.767