How can I do math involving significant figures in C++? I want this to work correct with measured data from chemistry and physics experiments. An example: 65 / 5 = 10. I would need to get rid of unneeded decimal places and replace some digits with 0s.
Thanks!
This may not be the most efficient way, but you can create a custom sig fig data type.
It can be a lot of work, but if you implement this right, it can be a really flexible way to represent and do calculations with sig figs.
It is hard because significant figures are a decimal concept, and computers speak binary. You can use decimal number classes (I don't know of any), or use boost::interval, which is the closest to what you certainly want to achieve.
Well there are good math libraries in math.h
Also storing your figures in floats, doubles or long doubles will allow for more precise operations.
Floats offer 7 significant digits while doubles offer 16 significant digits.
source
Also when printing out usually people use _snprintf or printf and you can format those doubles, floats to the precision you want like:
You can also:
Output:
here is a quick C++11 solution that worked for me:
That depends on how you are displaying them. If you are using the printf-family, you set the precision (
sprintf(buffer, "%.2f", myfloat)
). If you are using ostreams, you call the precision function to set the number of decimal places. If you are looking for the more scientific method of sig figs, you'll have to write a custom function that determines the precision based on the current value of the float.