If I have 2.55, how do I write only .55 and skip 2 in programming language?
Well you can do this to store it in another variable -
double a=2.55,b;
b =a-(long)a; // subtracting decimal part from a
printf("%.2f\n",b);
As pointed out by Mark Dickinson Sir in comment that this is not safe . So you can make use of function modf from <math.h>-
For example -
double a=-2.55,b,i;
b =modf(a,&i); // i will give integer part and b will give fraction part
printf("%.2f\n",b);
Use double modf(double value, double *iptr) to get the factional part. Use round() to get the best value near the requested precision.
double GetDecimalPlaces(double x, unsigned places) {
double ipart;
double fraction = modf(x, &ipart);
return fraction;
// or
double scale = pow(10.0, places);
return round(fraction * scale)/scale;
}
void GetDecimalPlaces_Test(double x, unsigned places) {
printf("x:%e places:%u -->", x, places);
printf("%#.*f\n", places, GetDecimalPlaces(x, places));
// Additional work needed if leading '0' is not desired.
}
int main(void) {
GetDecimalPlaces_Test(2.55, 2);
GetDecimalPlaces_Test(-2.55, 2);
GetDecimalPlaces_Test(2.05, 2);
GetDecimalPlaces_Test(0.0, 2);
GetDecimalPlaces_Test(0.0005, 2);
}
Output
x:2.550000e+00 places:2 -->0.55
x:-2.550000e+00 places:2 -->-0.55
x:2.050000e+00 places:2 -->0.05
x:0.000000e+00 places:2 -->0.00
x:5.000000e-04 places:2 -->0.00
One dirty trick is to cast your double to an int to get only the whole number. You can then subtract the two to get only the decimal part:
double d = 2.55;
double remainder = d - (int)d;
printf ("%.2f\n", remainder);
double values are not perfectly precise, so small rounding errors can get introduced. You can store the total number in an Integer. You can for example divide by 100 to get the value before the . and use % modulus to get the decimal values.
Example:
int main()
{
int num = 255;
printf("%d.%d\n", num / 100, num % 100); // prints 2.55
printf(".%d", num % 100); // prints .55
return 0;
}
This fails with negative numbers, but you can easily add cases to handle that.
Related
Here is my code:
#include <stdio.h>
#include <math.h>
double Mul(double X,double Y,double Z)
{
Y=Y*pow(10,6);
Y=Y+Z;
X=(X*pow(10,12))+Y;
//X=114360000000000000+117239051145;
//X=Y;
return X;
}
int main()
{
double Hello=Mul(114360,117239,511432);
printf("%f",Hello);
return 0;
}
The output should be "114360117239511432" but I got "114360117239511424" I need to know why 511432 converts to 511424? and How can I solve this problem?
I suggest to get familiar with floating point inaccuracy. However you use decimal numbers as parameters, they are not integers. If you want to know more of the integer limits, please check the numeric limits.
Let me be more specific. Double type become inaccurate if the exponent other than 1. I modified a bit your code, to show what are the exact values.
double Mul(double X, double Y, double Z)
{
double YbutMore = Y * pow(10, 6);
// YbutMore = 117239000000.00000
double YandZ = YbutMore + Z;
// YandZ = 117239511432.00000
double Xpow12 = X * pow(10, 12);
// Xpow12 = 1.1436000000000000e+17
return Xpow12 + Y;
// returns 1.1436000000011723e+17
}
So it all begins when we do a X * pow(10, 12). The mantissa cannot hold this big number, so the exponent will be other than 1 that will cause the inaccuracy. Don't forget to check the double value memory model.
If you are intrested how to store accurate and large numbers, please see How to store extremely large numbers?
I'm trying to print out the decimal expansion of a rational number in C. The problem I have is that when I divide the numerator by the denominator I lose precision. C rounds up the repeating part when I don't want it to.
For example, 1562/4995 = 0.3127127127... but in my program I get 1562/4995 = 0.312713. As you can see a part of the number that I need has been lost.
Is there a way to specify C to preserve a higher level of decimal precision?
I have tried to declare the result as a double, long double and float. I also tried to split the expansion into 2 integers seperated by a '.'
However both methods haven't been successful.
int main() {
int numerator, denominator;
numerator = 1562;
denominator = 4995;
double result;
result = (double) numerator / (double) denominator;
printf("%f\n", result);
return 0;
}
I expected the output to be 1562/4995 = 0.3127127127... but the actual output is 1562/4995 = 0.312713
The %f format specifier to printf shows 6 digits after the decimal point by default. If you want to show more digits, use a precision specifier:
printf("%.10f\n", result);
Also, the double type can only accurately store roughly 16 decimal digits of precision.
You need to change your output format, like this:
printf("%.10lf\n", result);
Note two things:
The value after the . specifies the decimal precision required (10 decimal places, here).
Note that I have added an l before the f to explicitly state that the argument is a double rather than a (single-precision) float.
EDIT: Note that, for the printf function, it is not strictly necessary to include the l modifier. However, when you come to use the 'corresponding' scanf function for input, it's absence will generate a warning and (probably) undefined behaviour:
scanf("%f", &result); // Not correct
scanf("%lf", &result); // Correct
If printing is all you want to do, you can do this with the same long division you were taught in elementary school:
#include <stdio.h>
/* Print the decimal representation of N/D with up to
P digits after the decimal point.
*/
#define P 60
static void PrintDecimal(unsigned N, unsigned D)
{
// Print the integer portion.
printf("%u.", N/D);
// Take the remainder.
N %= D;
for (int i = 0; i < P && N; ++i)
{
// Move to next digit position and print next digit.
N *= 10;
printf("%u", N/D);
// Take the remainder.
N %= D;
}
}
int main(void)
{
PrintDecimal(1562, 4995);
putchar('\n');
}
So i am trying to write a code which can allow me to round UP any number to 3 decimal places. My code for rounding up a number was like this :
for (rowIndex = 0; rowIndex < MAX_ROWS; rowIndex++)
{
for (columnIndex = 0; columnIndex < MAX_COLUMNS; columnIndex++)
{
printf("%.3f ", ceil(rawData[rowIndex][columnIndex] * 1000.0) / 1000.0);
}
}
But yesterday my teacher told us to use a code which has a structure like this:
float roundValue(float value, int decimalPlaces)
{
// Place rounding code here
return value;
}
i am not quite sure how to write the code in this format! I am a beginner in coding so this might be so silly.
UPDATE:
so i just read all the comments below and tried to write the code but still has a problem. my code is :
double roundValue(double value, int decimalPlaces)
{
value = roundf( value * pow(10, decimalPlaces)) / pow(10, decimalPlaces);
return value;
}
int main(void)
{
int rowIndex = 0;
int columnIndex = 0;
double rawData[MAX_ROWS][MAX_COLUMNS]; // 2-dimensional array to store our
raw data
double value = rawData[MAX_ROWS][MAX_COLUMNS];
int decimalPlaces = 3;
// Print out the roundup data array
printf(" --- ROUNDED DATA ---\n");
for (rowIndex = 0; rowIndex < MAX_ROWS; rowIndex++)
{
for (columnIndex = 0; columnIndex < MAX_COLUMNS; columnIndex++)
{
printf("%.3f ", roundValue(value, 3));
}
printf("\n");
}
return 0;
}
it gives me only 0 for all the numbers.
Based on this answer, you could use the roundf function found in math.h:
#include <stdio.h>
#include <math.h>
/* function that rounds a float to the specified number of decimals */
float roundValue(float value, int decimalPlaces)
{
value = roundf(value * pow(10, decimalPlaces)) / pow(10, decimalPlaces);
return value;
}
/*to see the results: */
int main()
{
float value = 12.34567;
printf("%f", roundValue(value, 3));
return 0;
}
Compilation/run:
$ gcc -lm main.c
$ ./a.out
12.346000
He just told you to write your code in a function that you can call in the main() function.
So instead of rewriting your code every time you need a round value you can use a function, you give it the number that you want to calculate the round value for, and it will give you the result so your code won't be repetitive
Essentially it can't be done. The problem is that 0.1, or 0.001, cannot be represented in floating point format exactly. So you can only round to the nearest representation rounded = floor(x * 1000 + 0.5)/1000.0. It's best to use the full accuracy of the double, then round at the last moment, for display.
printf("%.3g", x);
will achieve this for you. In combination with strtod it's also another technique for rounding.
.. to round UP any number to 3 decimal places.
my teacher told us to use a code ... like float roundValue(float value, int decimalPlaces)
Without going to higher precision, it is very difficult to meet OP's goal with the best answer for all value.
Rounding a floating pointer value a) up or b) to the nearest representable 0.001 (or 10-n) is usually done in steps.
1) Multiply by 10n
2) Round a) up or b) to nearest
3) Divide by 10n
float roundValue(float value, int decimalPlaces) {
// form the power of 10
assert(decimalPlaces >= 0 && decimalPlaces <= 9);
int power_of_10 = 1;
while (decimalPlaces-- > 0) power_of_10 *= 10;
double fpower_of_10 = power_of_10; // or just use `pow(10, decimalPlaces);
Scaling by a power of 10 introduces imprecision. This slight error is magnified in the rounding step. A simple work-around it to use higher precision math. Fortunately the coding goal started with a float value and double often has higher precision.
Scaling by a power-of 10 can cause overflow, yet that is not likely when value is float and the product is double which has a wider range.
double y = value * fpower_of_10;
// round
double rounded_y = ceil(y); // round up
// or
double rounded_y = round(y); // round to nearest
The quotient will rarely provide an exact multiple of 0.001 (or whatever power-of-10) but a floating point value that is near a multiple of 0.001.
y = rounded_y / fpower_of_10;
return y;
}
Usage follows. Recall that unless your floating point types use a FLT_RADIX == 10 (very rare these days, usually 2), The result with only be near the desired "number to n decimal places.". If done well, the result will be the nearest possible float/double.
printf("%f\n", roundValue(123.456789, 3));
printf("%.10f\n", roundValue(123.456789, 3)); // to see more
More: an easy way to avoid overflow issues if higher precision is not available or used is to recognize that great C floating-points values have no fractional part and need no rounding.
float roundValue(float value, int decimalPlaces) {
float int_ptr;
float frac_part = modff(value, &int_ptr);
if (frac_part == 0) return value;
double pow10 = pow(10, decimalPlaces);
return round(value * pow10)/pow10; // or ceil()
}
There are other small subtle issues not noted here. double rounding, NaN, rounding mode, round() vs. rint(), nearbyint().
I was trying to extract the exact fractional part from a floating point number. I tried with this:
float f=254.73;
int integer = (int)f;
float fractional = f-integer;
printf ("The fractional part is: %f", fractional);
But the output is: 0.729996. For this reason when I was doing this:
float f=254.73;
int integer = (int)f;
float fractional = f-integer;
int fractional_part_in_integer = ((int)(f*100)%100);
printf ("The value is: %d", fractional_part_in_integer);
It gives me 72 as output. But, I want to extract exactly 73 from the given number 254.73. I already know how to use %.2f during printf() function to print upto two decimal numbers. But in my code I don't want to print the number right now. I have some calculations with that fractional part as integer form i.e. 73.
So, my problem is how could I extract the fractional part from 254.73 so that I can get exact 73 as integer to do more calculations?
How to get the exact fractional part from a floating point number as an integer?
trying to extract the exact fractional part from a floating point number.
Use modf() or modff()
double modf(double value, double *iptr);
float modff(float value, float *iptr);
The modf functions break the argument value into integral and fractional parts, ...
C11 ยง7.12.6.12 2
#include <math.h>
double value = 1.234;
double ipart;
double frac = modf(value, &ipart);
A better approach for OP's need may be to first round a scaled value and then back into whole and fractional parts.
double value = 254.73;
value = round(value*100.0);
double frac = fmod(value, 100); // fmod computes the floating-point remainder of x/y.
double ipart = (value - frac)/100.0;
printf("%f %f\n", ipart, frac);
254.000000 73.000000
Ref detail: When OP uses 254.73, this is converted to the nearest float value which may be 254.729995727539....
float f = 254.73;
printf("%.30f\n", f);
// 254.729995727539062500000000000000
You can use sprintf and sscanf to print the value to a string and then extract the fraction. The %*d scans and discards the first integer of the formatted string. A dot is scanned and then the fraction.
#include <stdio.h>
int main( void)
{
char fp[30];
int fraction;
float f = 254.73f;
sprintf ( fp, "%.2f", f);
sscanf ( fp, "%*d.%d", &fraction);
printf ( "%d\n", fraction);
return 0;
}
The easiest way is to use standard library function ceil from <math.h>.
The float number 254.73 may be converted to 254.7299957275390625000000.
f-integer will give 0.7299957275390625000000.
Now multiply it by 100 and use ceil function to get the smallest integer value not less than 72.99957275390625000000.
int fractional_part_in_integer = ((int)ceil(fractional*100)) % 100;
UPDATE: As pointed in a comment by #Sneftel, the above suggested method in this answer will not work consistently.
A simple hack is to use round function from math.h to round the f and then extract the fractional part
float f=254.73;
int int_part = (int)f;
float fractional = round(f*100)/100 - int_part;
int fractional_part_in_integer = (int)(fractional*100);
printf("%d, %d\n ", int_part, fractional_part_in_integer);
Output:
254, 73
Take the number in string use the built-in function find() to find the position of ".".
#include <iostream>
using namespace std;
int main()
{
string f = "254.7356656";
int position = f.find(".");
cout << f.substr(position + 1);
return 0;
}
Output: 7356656
Is this even possible? i tried to google it but i cant seem to find the right answer.
I need to limit the decimal places since the answer will really differ if there is only 3 decimal places than 5, so i was hoping that you could help me with these. i know how to print with 3 decimal places but to declare a variable to only hold 3 decimal places is something i do not know. i could also use some links if you have any.
float sinfa(float num1)
{
float fc;
float powers;
float rad_angle;
rad_angle = num1 * (PI / 180.0);
powers = pow(num1,4);
fc = sin(rad_angle)-powers+1;
return (fc);
}
float sinfb(float num2)
{
float fd;
float powerss;
float rad_angle1;
rad_angle1 = num2 * (PI / 180.0);
powerss = pow(num2,4);
fd = sin(rad_angle1)-powerss+1;
return (fd);
}
float tp(float fa,float fb,float num1,float num2)
{
float p;
float fm2 = fa*num2;
float fm1 = fb*num1;
p = (fm2-fm1)/(fa-fb);
return (p);
}
float sinp(float p1)
{
float fop;
float ppowers;
float rad_angle2;
rad_angle2 = p1 * (PI / 180.0);
ppowers = pow(p1,4);
fop = sin(rad_angle2)-ppowers+1;
return (fop);
}
Thank you
Can't be done. A float is a 32-bit floating-point value in every C compiler I have ever used. There is nothing standard in the language to redefine how it works.
You could write a set of fixed-point functions that store values multiplied by 1000, or use a general library that implements fixed-point with arbitrary precision and set the precision to 3 decimal digits.
C++ fixed point library?
It can be done!
int intVal = 1.234567 * 1000; // result: 1234
float floatVal = (float)intVal / 1000; // result: 1.234
The trick is to:
Move the required number of digits to the left-hand side of the decimal place.
Truncate all the digits on the right-hand side of the decimal place.
Move the required number of digits back to the right-hand side of the decimal place.