ABCplus
ABCplus

Reputation: 4021

Print a double with its precision

I've got a third party library that read values from laboratory scales. This library interface many scale models, each one with its own precision. What I need to do in my C++ application (that uses that library) is to read the weight value from the scale (double format) and print it, taking into account the scale precision (so giving the user, reading that value, the information about scale precision).

So, connecting a scale with 2 decimals precision, the output should be for example: 23.45 g Instead, connecting a scale with 4 decimals precision, the output should be for example: 23.4567 g

The fact is I don't know from the library the scale precision. The function looks like the following:

double value = scale.Weight();

If I just print the double value, the output could be in the form of:

1.345999999999999

instead of:

1.346

Is there a way to understand the double precision so that the output shows the weight with the scale precision?

EDIT: scale precision goes from 0 to 6 decimals.

Upvotes: 0

Views: 103

Answers (1)

Logman
Logman

Reputation: 4189

No. This information should be inside scale class as double type has "fixed" precision and you cannot change it. Also type precision and printed precision are two different things. You can use type that has infinite precision but show always 2 digits after dot etc. If scale do not have precision information you could do a helper class and hard code precision inside it then correlate it with some scale property or type.

Upvotes: 1

Related Questions