Is it possible to round a double using just a printf statement? - c

Obviously this is just a fraction of the code.
printf("Please enter a positive number that has a fractional part with three or more decimal places\n");
scanf("%5.2d", &x);
printf("The number you have entered is %5.2d\n" ,x);
Would this automatically round the number I type in? Or is there another way to do this?
Edit:
printf("Please enter a positive number that has a fractional part with three or more decimal places\n");
scanf("%lf", &x);
x = x + 0.05;
printf( "The number you have entered is %5.2lf\n", x);
Iv done this, but Im taking into consideration what someone had said about printf just "changing" the way it reads out. So this is obviously not the right way. Should I implement maybe the pow() function? Will that work with this somehow?
Edit2:
printf("Please enter a positive number that has a fractional part with three or more decimal places\n");
scanf("%lf", &x);
x = x + 0.05;
printf( "The number you have entered is %5.2lf\n", x);
Okay, iv gotten to the point where if i imput a number it will round to a whole number. 35.21 will round to 35, and 35.51 will round to 36 et. etc.
How would I get 35.2178 to round to 35.22, and 35.2135 to round to 35.21.
How would I get the certain powers of the decimal to round instead of the whole number?

You really, really should not store "rounded" values in floating point variables. Floating point inaccuracy will ruin this - your 5.10 might become 5.099999999941892 simply because the implementation might not be able to store 5.10 exactly.
As an alternative, read the whole number, multiply it with 100 and convert it to int (which will round it towards zero). That will keep your calculations accurate.

"%.2f" will round a double to 2 digits. A double is not an integer, and %d and %f are not interchangeable.

{
float x;
float rounded_x;
printf("Please enter a positive number that has a fractional part with three or more decimal places\n");
scanf("%f", &x);
rounded_x = ((int)(x * 100 + .5) / 100.0);
printf( "The number you have entered is %.2f\n", rounded_x);
return 0;
}
Thank you to everyone who tried to help! I finally got it

printf won't change the value of the number, just how it is displayed. An alternative is
#include <math.h>
// round double x to 2 decimal places
x = 0.01 * floor(x * 100.0 + 0.5);

This doesn't make sense
scanf("%5.2d", &x);
You can't have an integer with numbers after the decmal point. if x is a flat then weird things will happen. If its an integer why are you after 2 decimal places in the printf.
What exactly are you trying to do?
Edit:
double x;
printf( "Please enter a positive number that has a fractional part with three or more decimal places\n" );
scanf( "%lf", &x );
printf( "The number you have entered is %5.2f\n", x + 0.005 );
I'm pretty sure printf only truncates. So you will need to add 0.005 to round it.

Related

why calculator I made not working? [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 4 years ago.
what i coded is
#include <stdio.h>
int main(){
float a, b;
printf("enter initial value.");
fflush(stdout);
scanf("%f", &a);
printf("add up the following number.");
fflush(stdout);
scanf("%f", &b);
printf("current value is %f.\n", (a+b));
fflush(stdout);
b = a+b;
printf("enter a value to subtract.");
fflush(stdout);
scanf("%f", &a);
printf("current value is %f. \n", b-a);
fflush(stdout);
b = b-a;
printf("enter a value to multiply.");
fflush(stdout);
scanf("%f", &a);
printf("current value is %f. \n", a*b);
fflush(stdout);
b = a*b;
printf("enter a value to devide.");
fflush(stdout);
scanf("%f", &a);
printf("current value is %f. \n", b/a);
fflush(stdout);
return 0;
}
Output:
enter initial value. 1000000
add up the following number. 9000000
current value is 10000000.000000.
enter a value to subtract. 0
current value is 10000000.000000.
enter a value to multiply. 1000000
current value is 10000000000000.000000.
enter a value to devide. 10
current value is 999999982796.800050.
https://i.stack.imgur.com/xuqab.png
i want 1000000000000.000000 as a result but 999999982796.800050 is all i've got....
what should i fix?
Single precision float can represent any real number for 6 decimal digits of precision. 999999982796.800050 meets that criteria.
This specific example may be fixed simply by using double, which is good for 15 decimal digits of precision.
If you must handle math with arbitrary precision for very large numbers, instead of using a float or double, look into an arbitrary precision library. A common on is called GMP
The idea behind an arbitrary precision library is the same as the idea behind how we do math as humans. A single "digit" can only store 10 possible values, but by creating an array of digits we can generate indiscriminately large values without losing accuracy.
Libraries like this utilize arrays and perform math one digit at a time in order to maintain perfect accuracy. They run a lot slower than floats or doubles, but if you care more about precision than speed then it's definitely the way to go.

C program to round numbers, rounded to second position after the decimal place [duplicate]

This question already has answers here:
How do I restrict a float value to only two places after the decimal point in C?
(17 answers)
Closed 8 years ago.
I am writing a simple program to round numbers. It works fine when I enter something like 1.4 (gives me 1.0) or 2.6 (gives me 3.0). But when I enter 1.45, it should give me 1.5 but it prints 1.0. Or for 2.85 (should be 2.9, it prints 3.0). How do I make this work? I cannot use any functions.
#include<stdio.h>
const float add = 0.5;
int main(void)
{
float v;
printf("Please enter a value to be rounded: ");
scanf("%f", &v);
v = v + add;
v = (int)v;
printf("The rounded value is %.2f", v);
return 0;
}
Try this code. You need to break your floating value into Modulus and Dividend.
#include<stdio.h>
int main(void)
{
float v;
int con, r_value, mul;
printf("Please enter a value to be rounded: ");
scanf("%f", &v);
mul=v*10;
con=mul%10;
r_value=mul/10;
if(con>=5)
r_value=r_value+1;
else
r_value=r_value;
printf("The rounded value is %.2d", r_value);
return 0;
}
Above code is modified to be used for Negative Numbers also.
float v;
int con, r_value, mul;
printf("Please enter a value to be rounded: ");
scanf("%f", &v);
mul=v*10;
con=mul%10;
r_value=mul/10;
if(v>0)
{
if(con>=5)
r_value=r_value+1;
else
r_value=r_value;
}
else if (v<0)
{
if(con<=-5)
r_value=r_value-1;
else
r_value=r_value;
}
printf("The rounded value is %.2d", r_value);
Int value simply removes the value after decimal point it does't round of to nearest number
In your case when you give 2.45
2.45 + 0.5 = 2.95
which is rounded off to 2(2.0 since your asking for precision) i.e the decimal part is truncated not rounded off.
Ints do not have decimal places, so a cast from float to int then back to float will leave only the integer value.
Your subject (rounding to the second decimal place) does not match your question (rounding to an arbitrary position based on the input). That makes it difficult to answer your question properly.
That said, your code
v = v + 0.5;
v = (int)v;
will round a number to the nearest integer. I'm not sure why you expect the int cast to do anything else.
You are using v = (int)v;, how can it give 1.5 for input of 1.45.
To get what you want, you can just print the decimal digits 1 less than in original, i.e.
Suppose you have 2.455 which has 3 decimal digits, you can just print that number using %.2f and it will automatically be rounded off.
You can do:
printf("%.2f", ((int)(v * 100 + 0.5) / 100.0));

How do you read an input value to a desired amount of digits after the decimal point?

What I am saying is that lets say the user inputs a floating point number for ex 4.624.
Then you you have to read this value using scanf and then you might use it to do some sort of calculation by plugging it in a formula or something similar. How can you read that number to two digits after the decimal point which in this case would be 4.62 so that's the number you use in the formula and not the whole number of 4.624.
float x = 4.624;
float x_truncated_to_two_decimal_places = floor(x*100.0) / 100.0;
or
float x_rounded_to_two_decimal_places = round(x*100.0) / 100.0;
depending on what you want.

Any differences with %.1f and %.01f?

When i compiles a program with this code:
int main()
{
float a;
scanf("%f", &a);
printf("%.1f\n", a); //Here
return 0;
}
There is no difference with this other:
int main()
{
float a;
scanf("%f", &a);
printf("%.01f\n", a); //Here
return 0;
}
Anybody can tell me why?
The number behind the period is the precision that specifies the number of digits after the decimal point of a floating-point value. The leading zero has no meanings.
The number before the period is the number that specifies the minimum field width. The leading zero will change the padding character from white space to 0.
The digits after the decimal point specify the precision - the minimum number of digits which will be written. .1 and .01 both say to put at least 1 digit, and to pad the result with zeros if there is fewer than 1 digit. Plain %f is equivalent to %.6f, i.e. 6 digits after the decimal point.
the output of first program will be for eg. a=100
for the both print command it would be
100.000000 (by default presicion of double is 6)
100.0
only.
where as the second program will have the value:
100.000000 (by default presicion of double)
100.0

Why do I get different results only 1% of the time?

I am trying to truncate everything past the hundredths decimal. (13.4396 would be 13.43) Sholdn't it always or never work?
I have this formula that works 99%:
input = (( (double) ((int)(orgInput * 100)) ) / 100) ;
Then I have this formula sequence that is arithmetically equivalent:
input = (orgInput * 100);
input = (int) input;
input = (double) (input);
input = input / 100;
These inputs do not give the desired result (Formula truncates and round down, while the broken down steps output the desired result):
12.33
99.99
22.22
44.32
56.78
11.11
And then an even bigger mystery to me is why 33.30 does not work on either of them. Below is my program that runs continuously to demonstrate my problem.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
double orgInput, input;
while (4!=3)
{
printf("Please enter the dollar amount (up to $100) => ");
scanf("%lf", &orgInput);
/* Truncates anything past hundredths place */
input = (orgInput * 100) ;
printf("\n1. input is %g \n ", input);
input = (int) input ;
printf("\n2. input is %g \n ", input);
input = (double) (input) ;
printf("\n3. input is %g \n", input);
input = input / 100 ;
printf("\n4. input is %.2lf \n", input);
input = (( (double) ((int)(orgInput * 100)) ) / 100) ;
printf("\nUsing the formula the input is %.2lf \n \n\n", input);
}
system("PAUSE");
return 0;
}
Thank you in advance!!!! P.S. Sorry for the formatting I am still getting used to stackoverflow
Key phrases:
Double to int conversion
Precision error
I think you are suffering from floating-point precision errors.
You should be able to fix this by doing:
const double epsilon = 1e-10; // Or some suitable small number
input = floor(orgInput * 100 + epsilon) / 100;
An alternative is to stop this from happening on input. Instead of reading in a double, you read a string and then parse that to get out the dollar and cents amount (cents being exactly 2 digits following the decimal point, if any). You can then ignore everything else.
In general, if you are working with money truncated to cents, you might be best to keep it in cents and use integers. Either that or round instead of truncate (for my above example, that would mean an epsilon of 0.5).
You need to understand that floats are represented in binary as:
2^(exponent) * mantissa
Exponent is a standard integer, but mantissa (a value between 1 and 2) is a number of bits where each bit represents a fraction: 1, 1/2, 1/4, 1/8, 1/16 and so on... Therefore it is not possible for the mantissa to represent certain values exactly, it will have an accuracy of +/- some fraction.
For example you mentioned 33.30. As a float 33.30 can only be: 2^5 * mantissa.
In this case the mantissa has to be 33.30/32 = 1.40625 exactly. But by making it out of the fractions the closest it can be is be is: 1.0406249999999999111821580299874767661094. So the actual value of the double is not 33.30, its 33.2999999999999971578290569595992565155029296875, which of course rounds DOWN to 33.29 when you do the type cast to integer.
The correct way to fix your program is not to scan in a float in the first place. You should be scanning in two integers seperated by decimal, and if scanf returns a value that indicates it did not scan two integers, then scan it as one integer for the case of a dollar only value.
Sadly, printf works by conversions to ints inside it and will not properly print any double precision floats that have more than 6 decimal places, which is why you see it as 33.30 even through you are asking printf to print the value of a double.
Most machines use binary, not decimal floating point. While binary-to-decimal conversion always gives exact values (in theory), it's impossible to convert from decimal to binary without rounding (I'm not considering the impractical case when numbers can have infinite number of digits).
As such, all your binary floating-point numbers are going to be slightly off of what they would've been in decimal.
The only 1-digit decimal fractions that can be represented in binary are: .0, .5.
Likewise, 2-digit decimal fractions exactly representable in binary are: .00, .25, .50, .75 (see here).
If you want, which I doubt, you can round to the nearest fraction of the four.

Resources