Take for example, the number 74.38145. The user inputs how many decimal points they wish to have displayed via the sprintf_s function.

I can't for the life of me figure out how to best do this. I know how to display the float to a set number of decimal points:

char output[50];
sprintf_s(output, "%.2f", currentValue);

How can I change the number 2 to allow for a variable number of decimal points to be displayed?

Thanks,

Kir.

Recommended Answers

All 2 Replies

I don't know of any way to do this... try iostreams in this case, they allow you to set precision formats as functions like setprecision(3) or whatever, this will allow a variable number.

Solved although to be honest, I'm pretty sure there is a better way of doing this... I didn't want to get into creating and destroying an iostream as this function potentially fires every loop of my programs execution. Thanks anyway though.

//Create the output text.
char output[50];
float decimalOutput = 0.0f;

//Ensure the decimal output retrieves the integer portion of the displayed value.
if(currentValue > 0)
	decimalOutput = floor(currentValue);
else
	decimalOutput = ceil(currentValue);

//Set decimalOutput to be the decimal section of the currentValue, then move the decimal point in accordance with the 'decimalPointVisuals' value.
decimalOutput = (currentValue - decimalOutput) * pow(10, (double)decimalPointVisuals);
if(decimalOutput > 0)
	decimalOutput = floor(decimalOutput);
else
	decimalOutput = ceil(decimalOutput);

//Display the newly created number with a specified number of decimal points.
sprintf_s(output, "%.0f.%.0f", floor(currentValue), decimalOutput);
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.