Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store price in double?

Tags:

c++

decimal

Is it safe to store prices in double variable in C++? In C# and Java you can use Decimal. (They also say that storing prices in double is very bad idea). What should I do in C++?

like image 483
user3555886 Avatar asked Apr 21 '14 07:04

user3555886


2 Answers

If the price range is suitable (probably it is), you can use long long with an implied dot before the last two digits. So, 12000 will mean 120.00. It's called "fixed point" arithmetic. But you need to take care of multiplications of two currency values (why would you need it anyway).

like image 62
cyco130 Avatar answered Oct 16 '22 11:10

cyco130


You can have a look at Intel® Decimal Floating-Point Math Library for storing price. Also you can check the Boost.Multiprecision library which can be very useful, you can use decimal based floating point template class called cpp_dec_float

like image 21
Rahul Tripathi Avatar answered Oct 16 '22 10:10

Rahul Tripathi