Two ints to one double C++ - c++

I am having a bit of a problem here.
I have two int values, one for dollars and one for cents. My job is to combine them into one double value and I am having some trouble.
Here's an example of what I want to be able to do:
int dollars = 10
int cents = 50
<some code which I haven't figured out yet>
double total = 10.50
I want to think it is relatively simple, but I'm having a hard time figuring it out.
Thanks for the help!

Start by thinking how you would solve this as a simple arithmetic problem, with pencil and paper (nothing to do with C). Once you find a way to do it manually, I'm sure the way to program it will seem trivial.

How about double total = double(dollars) + double(cents) / 100.0;?
Note that double is not a good data type to represent 10-based currencies, due to its inability to represent 1/100 precisely. Consider a fixed-point solution instead, or perhaps a decimal float (those are rare).

That's not difficult... you have to convert dollars to a double1 and add cents multiplied for 0.01 (or divided by 100. - notice the trailing dot, that's to indicate that 100. is a double constant, so / will perform a floating-point division instead of an integer division).
... but be aware of the fact that storing monetary values in binary floating-point variables is not a good idea at all, because binary doesn't have a finite representation of many "exact" decimal amounts (e.g. 0.1), that will be stored in an approximate representation. Working with such values may yield "strange" results when you start to do some arithmetic with them.
Actually, depending on your expression, it's probably not necessary due to implicit casts.

If you're interested in 'the whole idea' of programming and not only in getting your homework right, I suggest you think about this: "Is there any way I can represent a whole dollar as a certain amount of cents?" Why should you ask this? Because if you want to represent two different 'types' of certain values as one value, you need to 'normalize' them or 'standardize' them in a way so that there is not any data loss or corruption (or at least for the smaller problems).
Also I agree with Kerrek SB, representing money as double might not be the best solution.

Isn't it just as easy: total = dollars + (cents/100); ?
No reason to complicate this.

Related

What data type, scheme, and how many bits should be used to store a FOREX price? [duplicate]

I know that a float isn't appropriate to store currency values because of rounding errors. Is there a standard way to represent money in C++?
I've looked in the boost library and found nothing about it. In java, it seems that BigInteger is the way but I couldn't find an equivalent in C++. I could write my own money class, but prefer not to do so if there is something tested.
Don't store it just as cents, since you'll accumulate errors when multiplying for taxes and interest pretty quickly. At the very least, keep an extra two significant digits: $12.45 would be stored as 124,500. If you keep it in a signed 32 bit integer, you'll have $200,000 to work with (positive or negative). If you need bigger numbers or more precision, a signed 64 bit integer will likely give you all the space you'll need for a long time.
It might be of some help to wrap this value in a class, to give you one place for creating these values, doing arithmetic on them, and formatting them for display. This would also give you a central place to carry around which currency it being stored (USD, CAD, EURO, etc).
Having dealt with this in actual financial systems, I can tell you you probably want to use a number with at least 6 decimal places of precision (assuming USD). Hopefully since you're talking about currency values you won't go way out of whack here. There are proposals for adding decimal types to C++, but I don't know of any that are actually out there yet.
The best native C++ type to use here would be long double.
The problem with other approaches that simply use an int is that you have to store more than just your cents. Often financial transactions are multiplied by non-integer values and that's going to get you in trouble since $100.25 translated to 10025 * 0.000123523 (e.g. APR) is going cause problems. You're going to eventually end up in floating point land and the conversions are going to cost you a lot.
Now the problem doesn't happen in most simple situations. I'll give you a precise example:
Given several thousand currency values, if you multiply each by a percentage and then add them up, you will end up with a different number than if you had multiplied the total by that percentage if you do not keep enough decimal places. Now this might work in some situations, but you'll often be several pennies off pretty quickly. In my general experience making sure you keep a precision of up to 6 decimal places (making sure that the remaining precision is available for the whole number part).
Also understand that it doesn't matter what type you store it with if you do math in a less precise fashion. If your math is being done in single precision land, then it doesn't matter if you're storing it in double precision. Your precision will be correct to the least precise calculation.
Now that said, if you do no math other than simple addition or subtraction and then store the number then you'll be fine, but as soon as anything more complex than that shows up, you're going to be in trouble.
Look in to the relatively recent Intelr Decimal Floating-Point Math Library. It's specifically for finance applications and implements some of the new standards for binary floating point arithmetic (IEEE 754r).
The biggest issue is rounding itself!
19% of 42,50 € = 8,075 €. Due to the German rules for rounding this is 8,08 €. The problem is, that (at least on my machine) 8,075 can't be represented as double. Even if I change the variable in the debugger to this value, I end up with 8,0749999....
And this is where my rounding function (and any other on floating point logic that I can think of) fails, since it produces 8,07 €. The significant digit is 4 and so the value is rounded down. And that is plain wrong and you can't do anything about it unless you avoid using floating point values wherever possible.
It works great if you represent 42,50 € as Integer 42500000.
42500000 * 19 / 100 = 8075000. Now you can apply the rounding rule above 8080000. This can easily be transformed to a currency value for display reasons. 8,08 €.
But I would always wrap that up in a class.
I would suggest that you keep a variable for the number of cents instead of dollars. That should remove the rounding errors. Displaying it in the standards dollars/cents format should be a view concern.
You can try decimal data type:
https://github.com/vpiotr/decimal_for_cpp
Designed to store money-oriented values (money balance, currency rate, interest rate), user-defined precision. Up to 19 digits.
It's header-only solution for C++.
You say you've looked in the boost library and found nothing about there.
But there you have multiprecision/cpp_dec_float which says:
The radix of this type is 10. As a result it can behave subtly differently from base-2 types.
So if you're already using Boost, this should be good to currency values and operations, as its base 10 number and 50 or 100 digits precision (a lot).
See:
#include <iostream>
#include <iomanip>
#include <boost/multiprecision/cpp_dec_float.hpp>
int main()
{
float bogus = 1.0 / 3.0;
boost::multiprecision::cpp_dec_float_50 correct = 1.0 / 3.0;
std::cout << std::setprecision(16) << std::fixed
<< "float: " << bogus << std::endl
<< "cpp_dec_float: " << correct << std::endl;
return 0;
}
Output:
float: 0.3333333432674408
cpp_dec_float: 0.3333333333333333
*I'm not saying float (base 2) is bad and decimal (base 10) is good. They just behave differently...
** I know this is an old post and boost::multiprecision was introduced in 2013, so wanted to remark it here.
Know YOUR range of data.
A float is only good for 6 to 7 digits of precision, so that means a max of about +-9999.99 without rounding. It is useless for most financial applications.
A double is good for 13 digits, thus: +-99,999,999,999.99, Still be careful when using large numbers. Recognize the subtracting two similar results strips away much of the precision (See a book on Numerical Analysis for potential problems).
32 bit integer is good to +-2Billion (scaling to pennies will drop 2 decimal places)
64 bit integer will handle any money, but again, be careful when converting, and multiplying by various rates in your app that might be floats/doubles.
The key is to understand your problem domain. What legal requirements do you have for accuracy? How will you display the values? How often will conversion take place? Do you need internationalization? Make sure you can answer these questions before you make your decision.
Whatever type you do decide on, I would recommend wrapping it up in a "typedef" so you can change it at a different time.
It depends on your business requirements with regards to rounding. The safest way is to store an integer with the required precision and know when/how to apply rounding.
Store the dollar and cent amount as two separate integers.
Integers, always--store it as cents (or whatever your lowest currency is where you are programming for.) The problem is that no matter what you do with floating point someday you'll find a situation where the calculation will differ if you do it in floating point. Rounding at the last minute is not the answer as real currency calculations are rounded as they go.
You can't avoid the problem by changing the order of operations, either--this fails when you have a percentage that leaves you without a proper binary representation. Accountants will freak if you are off by a single penny.
I would recommend using a long int to store the currency in the smallest denomination (for example, American money would be cents), if a decimal based currency is being used.
Very important: be sure to name all of your currency values according to what they actually contain. (Example: account_balance_cents) This will avoid a lot of problems down the line.
(Another example where this comes up is percentages. Never name a value "XXX_percent" when it actually contains a ratio not multiplied by a hundred.)
The solution is simple, store to whatever accuracy is required, as a shifted integer. But when reading in convert to a double float, so that calculations suffer fewer rounding errors. Then when storing in the database multiply to whatever integer accuracy is needed, but before truncating as an integer add +/- 1/10 to compensate for truncation errors, or +/- 51/100 to round.
Easy peasy.
The GMP library has "bignum" implementations that you can use for arbitrary sized integer calculations needed for dealing with money. See the documentation for mpz_class (warning: this is horribly incomplete though, full range of arithmetic operators are provided).
One option is to store $10.01 as 1001, and do all calculations in pennies, dividing by 100D when you display the values.
Or, use floats, and only round at the last possible moment.
Often the problems can be mitigated by changing order of operations.
Instead of value * .10 for a 10% discount, use (value * 10)/100, which will help significantly. (remember .1 is a repeating binary)
I'd use signed long for 32-bit and signed long long for 64-bit. This will give you maximum storage capacity for the underlying quantity itself. I would then develop two custom manipulators. One that converts that quantity based on exchange rates, and one that formats that quantity into your currency of choice. You can develop more manipulators for various financial operations / and rules.
This is a very old post, but I figured I update it a little since it's been a while and things have changed. I have posted some code below which represents the best way I have been able to represent money using the long long integer data type in the C programming language.
#include <stdio.h>
int main()
{
// make BIG money from cents and dollars
signed long long int cents = 0;
signed long long int dollars = 0;
// get the amount of cents
printf("Enter the amount of cents: ");
scanf("%lld", &cents);
// get the amount of dollars
printf("Enter the amount of dollars: ");
scanf("%lld", &dollars);
// calculate the amount of dollars
long long int totalDollars = dollars + (cents / 100);
// calculate the amount of cents
long long int totalCents = cents % 100;
// print the amount of dollars and cents
printf("The total amount is: %lld dollars and %lld cents\n", totalDollars, totalCents);
}
As other answers have pointed out, you should either:
Use an integer type to store whole units of your currency (ex: $1) and fractional units (ex: 10 cents) separately.
Use a base 10 decimal data type that can exactly represent real decimal numbers such as 0.1. This is important since financial calculations are based on a base 10 number system.
The choice will depend on the problem you are trying to solve. For example, if you only need to add or subtract currency values then the integer approach might be sensible. If you are building a more complex system dealing with financial securities then the decimal data type approach may be more appropriate.
As another answer points out, Boost provides a base 10 floating point number type that serves as a drop-in replacement for the native C++ floating-point types, but with much greater precision. This might be convenient to use if your project already uses other Boost libraries.
The following example shows how to properly use this decimal type:
#include <iostream>
#include <boost/multiprecision/cpp_dec_float.hpp>
using namespace std;
using namespace boost::multiprecision;
int main() {
std::cout << std::setprecision(std::numeric_limits<cpp_dec_float_50>::max_digits10) << std::endl;
double d1 = 1.0 / 10.0;
cpp_dec_float_50 dec_incorrect = 1.0 / 10.0; // Incorrect! We are constructing our decimal data type from the binary representation of the double value of 1.0 / 10.0
cpp_dec_float_50 dec_correct(cpp_dec_float_50(1.0) / 10.0);
cpp_dec_float_50 dec_correct2("0.1"); // Constructing from a decimal digit string.
std::cout << d1 << std::endl; // 0.1000000000000000055511151231257827021181583404541015625
std::cout << dec_incorrect << std::endl; // 0.1000000000000000055511151231257827021181583404541015625
std::cout << dec_correct << std::endl; // 0.1
std::cout << dec_correct2 << std::endl; // 0.1
return 0;
}
Notice how even if we define a decimal data type but construct it from a binary representation of a double, then we will not obtain the precision that we expect. In the example above, both the double d1 and the cpp_dec_float_50 dec_incorrect are the same because of this. Notice how they are both "correct" to about 17 decimal places which is what we would expect of a double in a 64-bit system.
Finally, note that the boost multiprecision library can be significantly slower than the fastest high precision implementations available. This becomes evident at high digit counts (about 50+); at low digit counts the Boost implementation can be comparable other, faster implementations.
Sources:
https://www.boost.org/doc/libs/1_80_0/libs/multiprecision/doc/html/boost_multiprecision/tut/floats/fp_eg/floatbuiltinctor.html
https://www.boost.org/doc/libs/1_80_0/libs/multiprecision/doc/html/boost_multiprecision/tut/floats/fp_eg/caveats.html
Our financial institution uses "double". Since we're a "fixed income" shop, we have lots of nasty complicated algorithms that use double anyway. The trick is to be sure that your end-user presentation does not overstep the precision of double. For example, when we have a list of trades with a total in trillions of dollars, we got to be sure that we don't print garbage due to rounding issues.
go ahead and write you own money (http://junit.sourceforge.net/doc/testinfected/testing.htm) or currency () class (depending on what you need). and test it.

XCODE C++ Decimal/Money data type? [duplicate]

I know that a float isn't appropriate to store currency values because of rounding errors. Is there a standard way to represent money in C++?
I've looked in the boost library and found nothing about it. In java, it seems that BigInteger is the way but I couldn't find an equivalent in C++. I could write my own money class, but prefer not to do so if there is something tested.
Don't store it just as cents, since you'll accumulate errors when multiplying for taxes and interest pretty quickly. At the very least, keep an extra two significant digits: $12.45 would be stored as 124,500. If you keep it in a signed 32 bit integer, you'll have $200,000 to work with (positive or negative). If you need bigger numbers or more precision, a signed 64 bit integer will likely give you all the space you'll need for a long time.
It might be of some help to wrap this value in a class, to give you one place for creating these values, doing arithmetic on them, and formatting them for display. This would also give you a central place to carry around which currency it being stored (USD, CAD, EURO, etc).
Having dealt with this in actual financial systems, I can tell you you probably want to use a number with at least 6 decimal places of precision (assuming USD). Hopefully since you're talking about currency values you won't go way out of whack here. There are proposals for adding decimal types to C++, but I don't know of any that are actually out there yet.
The best native C++ type to use here would be long double.
The problem with other approaches that simply use an int is that you have to store more than just your cents. Often financial transactions are multiplied by non-integer values and that's going to get you in trouble since $100.25 translated to 10025 * 0.000123523 (e.g. APR) is going cause problems. You're going to eventually end up in floating point land and the conversions are going to cost you a lot.
Now the problem doesn't happen in most simple situations. I'll give you a precise example:
Given several thousand currency values, if you multiply each by a percentage and then add them up, you will end up with a different number than if you had multiplied the total by that percentage if you do not keep enough decimal places. Now this might work in some situations, but you'll often be several pennies off pretty quickly. In my general experience making sure you keep a precision of up to 6 decimal places (making sure that the remaining precision is available for the whole number part).
Also understand that it doesn't matter what type you store it with if you do math in a less precise fashion. If your math is being done in single precision land, then it doesn't matter if you're storing it in double precision. Your precision will be correct to the least precise calculation.
Now that said, if you do no math other than simple addition or subtraction and then store the number then you'll be fine, but as soon as anything more complex than that shows up, you're going to be in trouble.
Look in to the relatively recent Intelr Decimal Floating-Point Math Library. It's specifically for finance applications and implements some of the new standards for binary floating point arithmetic (IEEE 754r).
The biggest issue is rounding itself!
19% of 42,50 € = 8,075 €. Due to the German rules for rounding this is 8,08 €. The problem is, that (at least on my machine) 8,075 can't be represented as double. Even if I change the variable in the debugger to this value, I end up with 8,0749999....
And this is where my rounding function (and any other on floating point logic that I can think of) fails, since it produces 8,07 €. The significant digit is 4 and so the value is rounded down. And that is plain wrong and you can't do anything about it unless you avoid using floating point values wherever possible.
It works great if you represent 42,50 € as Integer 42500000.
42500000 * 19 / 100 = 8075000. Now you can apply the rounding rule above 8080000. This can easily be transformed to a currency value for display reasons. 8,08 €.
But I would always wrap that up in a class.
I would suggest that you keep a variable for the number of cents instead of dollars. That should remove the rounding errors. Displaying it in the standards dollars/cents format should be a view concern.
You can try decimal data type:
https://github.com/vpiotr/decimal_for_cpp
Designed to store money-oriented values (money balance, currency rate, interest rate), user-defined precision. Up to 19 digits.
It's header-only solution for C++.
You say you've looked in the boost library and found nothing about there.
But there you have multiprecision/cpp_dec_float which says:
The radix of this type is 10. As a result it can behave subtly differently from base-2 types.
So if you're already using Boost, this should be good to currency values and operations, as its base 10 number and 50 or 100 digits precision (a lot).
See:
#include <iostream>
#include <iomanip>
#include <boost/multiprecision/cpp_dec_float.hpp>
int main()
{
float bogus = 1.0 / 3.0;
boost::multiprecision::cpp_dec_float_50 correct = 1.0 / 3.0;
std::cout << std::setprecision(16) << std::fixed
<< "float: " << bogus << std::endl
<< "cpp_dec_float: " << correct << std::endl;
return 0;
}
Output:
float: 0.3333333432674408
cpp_dec_float: 0.3333333333333333
*I'm not saying float (base 2) is bad and decimal (base 10) is good. They just behave differently...
** I know this is an old post and boost::multiprecision was introduced in 2013, so wanted to remark it here.
Know YOUR range of data.
A float is only good for 6 to 7 digits of precision, so that means a max of about +-9999.99 without rounding. It is useless for most financial applications.
A double is good for 13 digits, thus: +-99,999,999,999.99, Still be careful when using large numbers. Recognize the subtracting two similar results strips away much of the precision (See a book on Numerical Analysis for potential problems).
32 bit integer is good to +-2Billion (scaling to pennies will drop 2 decimal places)
64 bit integer will handle any money, but again, be careful when converting, and multiplying by various rates in your app that might be floats/doubles.
The key is to understand your problem domain. What legal requirements do you have for accuracy? How will you display the values? How often will conversion take place? Do you need internationalization? Make sure you can answer these questions before you make your decision.
Whatever type you do decide on, I would recommend wrapping it up in a "typedef" so you can change it at a different time.
It depends on your business requirements with regards to rounding. The safest way is to store an integer with the required precision and know when/how to apply rounding.
Store the dollar and cent amount as two separate integers.
Integers, always--store it as cents (or whatever your lowest currency is where you are programming for.) The problem is that no matter what you do with floating point someday you'll find a situation where the calculation will differ if you do it in floating point. Rounding at the last minute is not the answer as real currency calculations are rounded as they go.
You can't avoid the problem by changing the order of operations, either--this fails when you have a percentage that leaves you without a proper binary representation. Accountants will freak if you are off by a single penny.
I would recommend using a long int to store the currency in the smallest denomination (for example, American money would be cents), if a decimal based currency is being used.
Very important: be sure to name all of your currency values according to what they actually contain. (Example: account_balance_cents) This will avoid a lot of problems down the line.
(Another example where this comes up is percentages. Never name a value "XXX_percent" when it actually contains a ratio not multiplied by a hundred.)
The solution is simple, store to whatever accuracy is required, as a shifted integer. But when reading in convert to a double float, so that calculations suffer fewer rounding errors. Then when storing in the database multiply to whatever integer accuracy is needed, but before truncating as an integer add +/- 1/10 to compensate for truncation errors, or +/- 51/100 to round.
Easy peasy.
The GMP library has "bignum" implementations that you can use for arbitrary sized integer calculations needed for dealing with money. See the documentation for mpz_class (warning: this is horribly incomplete though, full range of arithmetic operators are provided).
One option is to store $10.01 as 1001, and do all calculations in pennies, dividing by 100D when you display the values.
Or, use floats, and only round at the last possible moment.
Often the problems can be mitigated by changing order of operations.
Instead of value * .10 for a 10% discount, use (value * 10)/100, which will help significantly. (remember .1 is a repeating binary)
I'd use signed long for 32-bit and signed long long for 64-bit. This will give you maximum storage capacity for the underlying quantity itself. I would then develop two custom manipulators. One that converts that quantity based on exchange rates, and one that formats that quantity into your currency of choice. You can develop more manipulators for various financial operations / and rules.
This is a very old post, but I figured I update it a little since it's been a while and things have changed. I have posted some code below which represents the best way I have been able to represent money using the long long integer data type in the C programming language.
#include <stdio.h>
int main()
{
// make BIG money from cents and dollars
signed long long int cents = 0;
signed long long int dollars = 0;
// get the amount of cents
printf("Enter the amount of cents: ");
scanf("%lld", &cents);
// get the amount of dollars
printf("Enter the amount of dollars: ");
scanf("%lld", &dollars);
// calculate the amount of dollars
long long int totalDollars = dollars + (cents / 100);
// calculate the amount of cents
long long int totalCents = cents % 100;
// print the amount of dollars and cents
printf("The total amount is: %lld dollars and %lld cents\n", totalDollars, totalCents);
}
As other answers have pointed out, you should either:
Use an integer type to store whole units of your currency (ex: $1) and fractional units (ex: 10 cents) separately.
Use a base 10 decimal data type that can exactly represent real decimal numbers such as 0.1. This is important since financial calculations are based on a base 10 number system.
The choice will depend on the problem you are trying to solve. For example, if you only need to add or subtract currency values then the integer approach might be sensible. If you are building a more complex system dealing with financial securities then the decimal data type approach may be more appropriate.
As another answer points out, Boost provides a base 10 floating point number type that serves as a drop-in replacement for the native C++ floating-point types, but with much greater precision. This might be convenient to use if your project already uses other Boost libraries.
The following example shows how to properly use this decimal type:
#include <iostream>
#include <boost/multiprecision/cpp_dec_float.hpp>
using namespace std;
using namespace boost::multiprecision;
int main() {
std::cout << std::setprecision(std::numeric_limits<cpp_dec_float_50>::max_digits10) << std::endl;
double d1 = 1.0 / 10.0;
cpp_dec_float_50 dec_incorrect = 1.0 / 10.0; // Incorrect! We are constructing our decimal data type from the binary representation of the double value of 1.0 / 10.0
cpp_dec_float_50 dec_correct(cpp_dec_float_50(1.0) / 10.0);
cpp_dec_float_50 dec_correct2("0.1"); // Constructing from a decimal digit string.
std::cout << d1 << std::endl; // 0.1000000000000000055511151231257827021181583404541015625
std::cout << dec_incorrect << std::endl; // 0.1000000000000000055511151231257827021181583404541015625
std::cout << dec_correct << std::endl; // 0.1
std::cout << dec_correct2 << std::endl; // 0.1
return 0;
}
Notice how even if we define a decimal data type but construct it from a binary representation of a double, then we will not obtain the precision that we expect. In the example above, both the double d1 and the cpp_dec_float_50 dec_incorrect are the same because of this. Notice how they are both "correct" to about 17 decimal places which is what we would expect of a double in a 64-bit system.
Finally, note that the boost multiprecision library can be significantly slower than the fastest high precision implementations available. This becomes evident at high digit counts (about 50+); at low digit counts the Boost implementation can be comparable other, faster implementations.
Sources:
https://www.boost.org/doc/libs/1_80_0/libs/multiprecision/doc/html/boost_multiprecision/tut/floats/fp_eg/floatbuiltinctor.html
https://www.boost.org/doc/libs/1_80_0/libs/multiprecision/doc/html/boost_multiprecision/tut/floats/fp_eg/caveats.html
Our financial institution uses "double". Since we're a "fixed income" shop, we have lots of nasty complicated algorithms that use double anyway. The trick is to be sure that your end-user presentation does not overstep the precision of double. For example, when we have a list of trades with a total in trillions of dollars, we got to be sure that we don't print garbage due to rounding issues.
go ahead and write you own money (http://junit.sourceforge.net/doc/testinfected/testing.htm) or currency () class (depending on what you need). and test it.

how to take the root of a very large number?

given x=4 and y=1296;
we need to solve for z in z^x=y;
we can calculate z=6 in various ways;
Question is how do I find z if y is a very large number greater than 10^100? I obviously can't store that number as int, so how would I go about calculating z?
C++ implementation would be nice, if not, any solution will work.
It depends on the accuracy required. Since 1e100 cannot be exactly represented by a double, you have a problem.
This works, if you are willing to accept that it does not yield an exact solution. But then, I just said that 1e100 is not represented exactly as a double anyway. Thus, in MATLAB,
exp(log(1e100)/4)
ans =
1e+25
Ok, so it looks like 1e25 is the answer, but is it really? In fact, the number we really get, in terms of a double, is: 10000000000000026675773440.
One problem is the original number was not represented exactly anyway. So 1e100, when stored in the IEEE format, is more accurately stored as something like this:
1.00000000000000001590289110975991804683608085639452813897813e100
To solve this exactly, you would best be served by a big integer form, but a big decimal form would do reasonably well too.
Thus, in MATLAB, using my big decimal (HPF) form we see that 1e100 is exactly represented in 100 digits of precision.
x = hpf('1e100',100)
x =
1.e100
And, to 100 digits of precision, the root is correct.
exp(log(x)/4)
ans =
10000000000000000000000000
Actually though, be careful, as any floating point form cannot represent real numbers exactly. To more precision, we see that the number computed was actually slightly in error:
9999999999999999999999999.9999999999999999999999999999999999999999999999999999999999999999999999999999999999800
A big integer form will yield an exact result, if one exists. Thus, using a big integer form, we see the expected result:
vpi(10)^100
ans =
10000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000
nthroot(vpi(10)^100,4)
ans =
10000000000000000000000000
The point is, to do the computation you desire, you need to use tools that can do the computation. There are many such big decimal or big integer tools to be had. For example, Java has a BigDecimal and a BigInteger form that I have used on occasion (though I've written my own tools anyway, thus in MATLAB, HPF and VPI.)
Maybe you can do something evil with logarithms
maybe there is a library that you can find that lets you deal with big integers
You can try to use Newton's method. In this case you need to use arbitrary-precision arithmetic.
I.e. you need to write class for arbitrary-precision number. It would be composition of mantissa, which is represented by array of digits and exponent, which is represented by integer. You should realize basic operations on numbers similar to pencil-and-paper methods. Then you should realize Newton's algoriithm as described in wiki.

C++: how to truncate the double in efficient way?

I would like to truncate the float to 4 digits.
Are there some efficient way to do that?
My current solution is:
double roundDBL(double d,unsigned int p=4)
{
unsigned int fac=pow(10,p);
double facinv=1.0/static_cast<double>(fac);
double x=static_cast<unsigned int>(d*fac)*facinv;
return x;
}
but using pow and delete seems to me not so efficient.
kind regards
Arman.
round(d*10000.0)/10000.0;
or if p must be variable;
double f = pow(10,p);
round(d*f)/f;
round will usually be compiled as a single instruction that is faster than converting to an integer and back. Profile to verify.
Note that a double may not have an accurate representation to 4 decimal places. You will not truly be able to truncate an arbitrary double, just find the nearest approximation.
Efficiency depends on your platform.
Whatever methods you try, you should profile to make sure
the efficiency is required (and a straightforward implementation is not fast enough for you)
the method you're trying is faster than others for your application on real data
You could multiply by 10000, truncate as an integer, and divide again. Converting between double and int might be faster or slower for you.
You could truncate on output, e.g. a printf format string of "%.4f"
You could replace pow with a more efficient integer-based variant instead. There's one here on Stack Overflow: The most efficient way to implement an integer based power function pow(int, int)
Also, if you can accept some inaccuracy, replace the divide with a multiply. Divisions are one of the slowest common math operations.
Other than that, I'll echo what others have said and simply truncate on output, unless you actually need to use the truncated double in calculations.
If you need to perform exact calculations that involve decimal digits, then stop using double right now! It's not the right data type for your purpose. You will not get actually rounded decimal values. Almost all values will (after truncation, not matter what method you use) be in fact be something like 1,000999999999999841, not 1,0001.
That's because double is implemented using binary fractions, not decimal ones. There are decimal types you can use instead that will work correctly. They will be a lot slower, but then, if the result does not need to be correct, I know a method to make it infinitely fast...

Best way to store currency values in C++

I know that a float isn't appropriate to store currency values because of rounding errors. Is there a standard way to represent money in C++?
I've looked in the boost library and found nothing about it. In java, it seems that BigInteger is the way but I couldn't find an equivalent in C++. I could write my own money class, but prefer not to do so if there is something tested.
Don't store it just as cents, since you'll accumulate errors when multiplying for taxes and interest pretty quickly. At the very least, keep an extra two significant digits: $12.45 would be stored as 124,500. If you keep it in a signed 32 bit integer, you'll have $200,000 to work with (positive or negative). If you need bigger numbers or more precision, a signed 64 bit integer will likely give you all the space you'll need for a long time.
It might be of some help to wrap this value in a class, to give you one place for creating these values, doing arithmetic on them, and formatting them for display. This would also give you a central place to carry around which currency it being stored (USD, CAD, EURO, etc).
Having dealt with this in actual financial systems, I can tell you you probably want to use a number with at least 6 decimal places of precision (assuming USD). Hopefully since you're talking about currency values you won't go way out of whack here. There are proposals for adding decimal types to C++, but I don't know of any that are actually out there yet.
The best native C++ type to use here would be long double.
The problem with other approaches that simply use an int is that you have to store more than just your cents. Often financial transactions are multiplied by non-integer values and that's going to get you in trouble since $100.25 translated to 10025 * 0.000123523 (e.g. APR) is going cause problems. You're going to eventually end up in floating point land and the conversions are going to cost you a lot.
Now the problem doesn't happen in most simple situations. I'll give you a precise example:
Given several thousand currency values, if you multiply each by a percentage and then add them up, you will end up with a different number than if you had multiplied the total by that percentage if you do not keep enough decimal places. Now this might work in some situations, but you'll often be several pennies off pretty quickly. In my general experience making sure you keep a precision of up to 6 decimal places (making sure that the remaining precision is available for the whole number part).
Also understand that it doesn't matter what type you store it with if you do math in a less precise fashion. If your math is being done in single precision land, then it doesn't matter if you're storing it in double precision. Your precision will be correct to the least precise calculation.
Now that said, if you do no math other than simple addition or subtraction and then store the number then you'll be fine, but as soon as anything more complex than that shows up, you're going to be in trouble.
Look in to the relatively recent Intelr Decimal Floating-Point Math Library. It's specifically for finance applications and implements some of the new standards for binary floating point arithmetic (IEEE 754r).
The biggest issue is rounding itself!
19% of 42,50 € = 8,075 €. Due to the German rules for rounding this is 8,08 €. The problem is, that (at least on my machine) 8,075 can't be represented as double. Even if I change the variable in the debugger to this value, I end up with 8,0749999....
And this is where my rounding function (and any other on floating point logic that I can think of) fails, since it produces 8,07 €. The significant digit is 4 and so the value is rounded down. And that is plain wrong and you can't do anything about it unless you avoid using floating point values wherever possible.
It works great if you represent 42,50 € as Integer 42500000.
42500000 * 19 / 100 = 8075000. Now you can apply the rounding rule above 8080000. This can easily be transformed to a currency value for display reasons. 8,08 €.
But I would always wrap that up in a class.
I would suggest that you keep a variable for the number of cents instead of dollars. That should remove the rounding errors. Displaying it in the standards dollars/cents format should be a view concern.
You can try decimal data type:
https://github.com/vpiotr/decimal_for_cpp
Designed to store money-oriented values (money balance, currency rate, interest rate), user-defined precision. Up to 19 digits.
It's header-only solution for C++.
You say you've looked in the boost library and found nothing about there.
But there you have multiprecision/cpp_dec_float which says:
The radix of this type is 10. As a result it can behave subtly differently from base-2 types.
So if you're already using Boost, this should be good to currency values and operations, as its base 10 number and 50 or 100 digits precision (a lot).
See:
#include <iostream>
#include <iomanip>
#include <boost/multiprecision/cpp_dec_float.hpp>
int main()
{
float bogus = 1.0 / 3.0;
boost::multiprecision::cpp_dec_float_50 correct = 1.0 / 3.0;
std::cout << std::setprecision(16) << std::fixed
<< "float: " << bogus << std::endl
<< "cpp_dec_float: " << correct << std::endl;
return 0;
}
Output:
float: 0.3333333432674408
cpp_dec_float: 0.3333333333333333
*I'm not saying float (base 2) is bad and decimal (base 10) is good. They just behave differently...
** I know this is an old post and boost::multiprecision was introduced in 2013, so wanted to remark it here.
Know YOUR range of data.
A float is only good for 6 to 7 digits of precision, so that means a max of about +-9999.99 without rounding. It is useless for most financial applications.
A double is good for 13 digits, thus: +-99,999,999,999.99, Still be careful when using large numbers. Recognize the subtracting two similar results strips away much of the precision (See a book on Numerical Analysis for potential problems).
32 bit integer is good to +-2Billion (scaling to pennies will drop 2 decimal places)
64 bit integer will handle any money, but again, be careful when converting, and multiplying by various rates in your app that might be floats/doubles.
The key is to understand your problem domain. What legal requirements do you have for accuracy? How will you display the values? How often will conversion take place? Do you need internationalization? Make sure you can answer these questions before you make your decision.
Whatever type you do decide on, I would recommend wrapping it up in a "typedef" so you can change it at a different time.
It depends on your business requirements with regards to rounding. The safest way is to store an integer with the required precision and know when/how to apply rounding.
Store the dollar and cent amount as two separate integers.
Integers, always--store it as cents (or whatever your lowest currency is where you are programming for.) The problem is that no matter what you do with floating point someday you'll find a situation where the calculation will differ if you do it in floating point. Rounding at the last minute is not the answer as real currency calculations are rounded as they go.
You can't avoid the problem by changing the order of operations, either--this fails when you have a percentage that leaves you without a proper binary representation. Accountants will freak if you are off by a single penny.
I would recommend using a long int to store the currency in the smallest denomination (for example, American money would be cents), if a decimal based currency is being used.
Very important: be sure to name all of your currency values according to what they actually contain. (Example: account_balance_cents) This will avoid a lot of problems down the line.
(Another example where this comes up is percentages. Never name a value "XXX_percent" when it actually contains a ratio not multiplied by a hundred.)
The solution is simple, store to whatever accuracy is required, as a shifted integer. But when reading in convert to a double float, so that calculations suffer fewer rounding errors. Then when storing in the database multiply to whatever integer accuracy is needed, but before truncating as an integer add +/- 1/10 to compensate for truncation errors, or +/- 51/100 to round.
Easy peasy.
The GMP library has "bignum" implementations that you can use for arbitrary sized integer calculations needed for dealing with money. See the documentation for mpz_class (warning: this is horribly incomplete though, full range of arithmetic operators are provided).
One option is to store $10.01 as 1001, and do all calculations in pennies, dividing by 100D when you display the values.
Or, use floats, and only round at the last possible moment.
Often the problems can be mitigated by changing order of operations.
Instead of value * .10 for a 10% discount, use (value * 10)/100, which will help significantly. (remember .1 is a repeating binary)
I'd use signed long for 32-bit and signed long long for 64-bit. This will give you maximum storage capacity for the underlying quantity itself. I would then develop two custom manipulators. One that converts that quantity based on exchange rates, and one that formats that quantity into your currency of choice. You can develop more manipulators for various financial operations / and rules.
This is a very old post, but I figured I update it a little since it's been a while and things have changed. I have posted some code below which represents the best way I have been able to represent money using the long long integer data type in the C programming language.
#include <stdio.h>
int main()
{
// make BIG money from cents and dollars
signed long long int cents = 0;
signed long long int dollars = 0;
// get the amount of cents
printf("Enter the amount of cents: ");
scanf("%lld", &cents);
// get the amount of dollars
printf("Enter the amount of dollars: ");
scanf("%lld", &dollars);
// calculate the amount of dollars
long long int totalDollars = dollars + (cents / 100);
// calculate the amount of cents
long long int totalCents = cents % 100;
// print the amount of dollars and cents
printf("The total amount is: %lld dollars and %lld cents\n", totalDollars, totalCents);
}
As other answers have pointed out, you should either:
Use an integer type to store whole units of your currency (ex: $1) and fractional units (ex: 10 cents) separately.
Use a base 10 decimal data type that can exactly represent real decimal numbers such as 0.1. This is important since financial calculations are based on a base 10 number system.
The choice will depend on the problem you are trying to solve. For example, if you only need to add or subtract currency values then the integer approach might be sensible. If you are building a more complex system dealing with financial securities then the decimal data type approach may be more appropriate.
As another answer points out, Boost provides a base 10 floating point number type that serves as a drop-in replacement for the native C++ floating-point types, but with much greater precision. This might be convenient to use if your project already uses other Boost libraries.
The following example shows how to properly use this decimal type:
#include <iostream>
#include <boost/multiprecision/cpp_dec_float.hpp>
using namespace std;
using namespace boost::multiprecision;
int main() {
std::cout << std::setprecision(std::numeric_limits<cpp_dec_float_50>::max_digits10) << std::endl;
double d1 = 1.0 / 10.0;
cpp_dec_float_50 dec_incorrect = 1.0 / 10.0; // Incorrect! We are constructing our decimal data type from the binary representation of the double value of 1.0 / 10.0
cpp_dec_float_50 dec_correct(cpp_dec_float_50(1.0) / 10.0);
cpp_dec_float_50 dec_correct2("0.1"); // Constructing from a decimal digit string.
std::cout << d1 << std::endl; // 0.1000000000000000055511151231257827021181583404541015625
std::cout << dec_incorrect << std::endl; // 0.1000000000000000055511151231257827021181583404541015625
std::cout << dec_correct << std::endl; // 0.1
std::cout << dec_correct2 << std::endl; // 0.1
return 0;
}
Notice how even if we define a decimal data type but construct it from a binary representation of a double, then we will not obtain the precision that we expect. In the example above, both the double d1 and the cpp_dec_float_50 dec_incorrect are the same because of this. Notice how they are both "correct" to about 17 decimal places which is what we would expect of a double in a 64-bit system.
Finally, note that the boost multiprecision library can be significantly slower than the fastest high precision implementations available. This becomes evident at high digit counts (about 50+); at low digit counts the Boost implementation can be comparable other, faster implementations.
Sources:
https://www.boost.org/doc/libs/1_80_0/libs/multiprecision/doc/html/boost_multiprecision/tut/floats/fp_eg/floatbuiltinctor.html
https://www.boost.org/doc/libs/1_80_0/libs/multiprecision/doc/html/boost_multiprecision/tut/floats/fp_eg/caveats.html
Our financial institution uses "double". Since we're a "fixed income" shop, we have lots of nasty complicated algorithms that use double anyway. The trick is to be sure that your end-user presentation does not overstep the precision of double. For example, when we have a list of trades with a total in trillions of dollars, we got to be sure that we don't print garbage due to rounding issues.
go ahead and write you own money (http://junit.sourceforge.net/doc/testinfected/testing.htm) or currency () class (depending on what you need). and test it.