I tried searching this up on Stack Overflow but couldn't find an answer.
Here is the code:
#include <stdio.h>
int main(void) {
double y;
printf("Enter a number: ");
scanf("%lf", &y);
printf("Your number when rounded is: %.2lf", y);
//If user inputs 5.05286, how can i round off this number so as to get the output as 5.00
//I want the output to be rounded as well as to be 2 decimal places like 10.6789 becomes 11.00
return 0;
}
I want to round a number, for example, if the number is 5.05286, it should be rounded to 5.00, and if it is 5.678901, it will be rounded to 6.00 with 2decimal places. The number 5.678901 is getting rounded to 5.05 but it should round to 5. I am aware that I can use floor() and ceil(), but I don't think I will be able to round off the answer without conditional statements, which is not the scope of my C knowledge. I also tried to use the round() function but it doesn't round at all.
You need to import <math.h> header :
#include <math.h> //don't forget to import this !
double a;
a = round(5.05286); //will be rounded to 5.00
This function has analog definitions for every type, which means that you can pass the following types and it'll be rounded to the nearest for every one of them :
double round(double a);
float roundf(float a);
long double roundl(long double a);
If you don't want to use any additional header:
float x = 5.65286;
x = (int)(x+0.5);
printf("%.2f",x);
Related
float number = 123.8798831;
number=(floorf((number + number * 0.1) * 100.0)) / 100.0;
printf("number = %f",number);
I want to get number = 136.25
But the compiler shows me number = 136.259995
I know that I can write like this printf("number = %.2f",number) ,but I need the number itself for further operation.It is necessary that the number be stored in a variable as number = 136.25
It is necessary that the number be stored in a variable as number = 136.25
But that would be the incorrect result. The precise result of number + number * 0.1 is 136.26787141. When you round that downwards to 2 decimal places, the number that you would get is 136.26, and not 136.25.
However, there is no way to store 136.26 in a float because it simply isn't a representable value (on your system). Best you can get is a value that is very close to it. You have successfully produced a floating point number that is very close to 136.26. If you cannot accept the slight error in the value, then you shouldn't be using finite precision floating point arithmetic.
If you wish to print the value of a floating point number up to limited number of decimals, you must understand that not all values can be represented by floating point numbers, and that you must use %.2f to get desired output.
Round float to 2 decimal places in C language?
Just like you did:
multiply with 100
round
divide by 100
I agree with the other comments/answers that using floating point numbers for money is usually not a good idea, not all numbers can be stored exactly. Basically, when you use floating point numbers, you sacrifice exactness for being able to storage very large and very small numbers and being able to store decimals. You don't want to sacrifice exactness when dealing with real money, but I think this is a student project, and no actual money is being calculated, so I wrote the small program to show one way of doing this.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(void)
{
double number, percent_interest, interest, result, rounded_result;
number = 123.8798831;
percent_interest = 0.1;
interest = (number * percent_interest)/100; //Calculate interest of interest_rate percent.
result = number + interest;
rounded_result = floor(result * 100) / 100;
printf("number=%f, percent_interest=%f, interest=%f, result=%f, rounded_result=%f\n", number, percent_interest, interest, result, rounded_result);
return EXIT_SUCCESS;
}
As you can see, I use double instead float, because double has more precession and floating point constants are of type double not float. The code in your question should give you a warning because in
float number = 123.8798831;
123.8798831 is of type double and has to be converted to float (possibly losing precession in the process).
You should also notice that my program calculates interest at .1% (like you say you want to do) unlike the code in your question which calculates interest at 10%. Your code multiplies by 0.1 which is 10/100 or 10%.
Here is an example of a function you can use for rounding to x number of decimals.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stddef.h>
double dround(double number, int dp)
{
int charsNeeded = 1 + snprintf(NULL, 0, "%.*f", dp, number);
char *buffer = malloc(charsNeeded);
snprintf(buffer, charsNeeded, "%.*f", dp, number);
double result = atof(buffer);
free(buffer);
return result;
}
int main()
{
float number = 37.777779;
number = dround(number,2);
printf("Number is %f\n",number);
return 0;
}
I'm solving a problem in Toph . In this problem I've to find out the empty space of a rectangle which has 2 equal circles in it.
here is the problem
#include <stdio.h>
float pi=3.1416;
int main()
{
int i,t;
float r,rest;
scanf("%d",&t);
for(i=1;i<=t;i++)
{
scanf("%f",&r);
rest=(4*r*2*r)-(2*pi*r*r);
printf("Case %d: %.2f\n",i,rest);
}
return 0;
Here is my solve. It returns a correct value for first test case but it fails to solve the second one.
What's the problem???
float pi=3.1416; is the cause of the problem. Under the math header file (#include <math.h>) there is a constant M_PI use it instead.
Edit:
Sorry, didn't read thoroughly, apparently the problem is in the floating point precision. If you change all float values into double it should work.
#include <stdio.h>
double pi=3.1416;
int main()
{
int i,t;
double r,rest;
scanf("%d",&t);
for(i=1;i<=t;i++)
{
scanf("%lf",&r);
rest=(4*r*2*r)-(2*pi*r*r);
printf("Case %d: %.2lf\n",i,rest);
}
return 0;
}
Unlike 2 and 8, the reason double is more accurate is because float cannot represent 3.1416 as well as the input values:
3.1416 -> 3.1415998935699462890625
40.082 -> 40.082000732421875
85.8 -> 85.8000030517578125
There's simply not enough precision, (note that IEEE-754 float, which is overwhelmingly used for float, stores it in base-2.) Most probably, the later numbers were probably specifically generated in order to fail the test cases. If one wants to know more, Don’t Store That in a Float, and What Every Computer Scientist Should Know About Floating-Point Arithmetic.
The numerical constant is 1.7168, which is exact assuming their version of pi, (times r*r.) The best one could with single-point precision is 1.7167999744415283203125, which is off by 2.55584716796875E-8. With a double, it's 1.71680000000000010373923942097, off by 1.0373923942097E-16, plus the values input.
I don't understand why doesn't the roundf() function from math.h round the donation variable, whilst it rounds livestockPM without a problem. I need to use the rounded values for other calculations, but I'm using printf to check if the values are correct, and it simply returns wrong values (doesn't round variable donation). Also, the variable final only returns values as if rounded to .00, doesn't matter what variables farmer1,2,3 hold.
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main(){
int farmer1 = 9940;
int farmer2 = 4241;
int farmer3 = 7779;
float livestockPM = (float)farmer1 / (float)farmer2;
printf("livestock: %f\n",livestockPM);
livestockPM = roundf(livestockPM * 100) / 100;
printf("livestock rounded: %f\n",livestockPM);
float donation = (float)livestockPM * (float)farmer3;
printf("donation: %f\n", donation);
donation = roundf(donation * 100.00) / 100.00;
printf("donation rounded: %f\n", donation);
float final = donation * (float)farmer2;
printf("final: %f\n", final);
return 0;
}
Output:
livestock: 2.343787
livestock rounded: 2.340000
donation: 18202.859375
donation rounded: 18202.859375
final: 77198328.000000
Anyone got any idea why? I was thinking because of multiplying float with int, but I can't seem to get it work like this. I've tried removing the (float) from integer variables, but the results were undesirable as well. Thanks.
OP's float is encoded using binary floating point and 18202.859375 lacks precision to take on a value that "%f" prints as 18202.860000.
A float cannot represent every possible number. As a binary floating point number it can represent numbers like below. See IEEE 754 Converter, but not in between.
18202.859375
18202.86138125
When the following executes, the best possible result is again 18202.859375.
float donation_rounded = roundf(18202.859375 * 100.00) / 100.00;
Recall that printf("%f\n", x) prints a number rounded textually to the closest 0.000001 value.
Code could use double, but the same problem will occur with very large numbers, but may meet OP''s immediate need. #user3386109
As OP appears to be trying to cope with money, there is no great solution in standard C. best money/currency representation goes into some of the issues.
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));
I like to change the number of decimal digits showed whenever I use a float number in C. Does it have something to do with the FLT_DIG value defined in float.h? If so, how could I change that from 6 to 10?
I'm getting a number like 0.000000 while the actual value is 0.0000003455.
There are two separate issues here: The precision of the floating point number stored, which is determined by using float vs double and then there's the precision of the number being printed as such:
float foo = 0.0123456789;
printf("%.4f\n", foo); // This will print 0.0123 (4 digits).
double bar = 0.012345678912345;
printf("%.10lf\n", bar); // This will print 0.0123456789
I experimented this problem and I found out that you cannot have great precision with float they are really bad .But if you use double it would give you the right answer. just mention %.10lf for precision upto 10 decimal points
You're running out of precision. Floats don't have great precision, if you want more decimal places, use the double data type.
Also, it seems that you're using printf() & co. to display the numbers - if you ever decide to use doubles instead of floats, don't forget to change the format specifiers from %f to %lf - that's for a double.
#kosmoplan - thank you for a good question!
#epsalon - thank you for a good response. My first thought, too, was "float" vs. "double". I was mistaken. You hit it on the head by realizing it was actually a "printf/format" issue. Good job!
Finally, to put to rest some lingering peripheral controversy:
/*
SAMPLE OUTPUT:
a=0.000000, x=0.012346, y=0.012346
a=0.0000003455, x=0.0123456791, y=0.0123456789
*/
#include <stdio.h>
int
main (int argc, char *argv[])
{
float x = 0.0123456789, a = 0.0000003455;
double y = 0.0123456789;
printf ("a=%f, x=%f, y=%lf\n", a, x, y);
printf ("a=%.10f, x=%.10f, y=%.10lf\n", a, x, y);
return 0;
}