116k views
4 votes
How to solve a program that accepts a number as input and prints just the decimal portion

Enter a number 15.789
Output 0.789

User AlphaBeta
by
5.4k points

2 Answers

5 votes

Answer:

We can extract the decimal part of a number by casting the variable

Step-by-step explanation:

Type casting is the process of converting one datatype into another one. Basically, most of the languagues support type casting and we can use it in advantage to get the decimal part of a number. Let assume you have a decimal number stored in your code, then let's do the following:

int integer_part = (int) float_number;

This is a typlical way to cast a float number into a integer one. By doing so, you are getting the integer part of a float number while the decimal portion is discarded.

Now you have a float number and a variable with its integer part. Decimal portion is computed as follows:

float decimal_part = float_number - integer_part;

You can follow this scheme in any programming language with strong typing (datatypes required to define a variable) and it will work ok.

User TJD
by
5.6k points
0 votes

Answer:

There are 2 ways to do extract the decimal part:

Step-by-step explanation:

  • First method using number

int main() {

double doublenum = 24.535;

int integerpart = (int)doublenum;

double decimalpart = num - integerpart;

printf(""Num = %f, integerpart = %d, decimalpart = %f\\"", doublenum, integerpart, decimalpart);

}

  • Second method using string:

#include <stdlib.h>

int main()

{

char* inStr = ""193.789"";

char* endptrvar;

char* loc = strchr(inStr, '.');

long mantissaval = strtod(loc+1, endptrvar);

long wholenum = strtod(inStr, endptrvar);

printf(""whole: %d \\"", wholenum);

printf(""mantissa: %d"", mantissaval);

}

User Eugene Chong
by
5.5k points