Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the Decimal part out of a float number

I need to get the decimal part out of a float number, for example:

float x = 18.30;

I need a way to get the '.30' in another float.. so I will have a float equals to 18.30 and another one equals to .30

Any ideas?

like image 919
newton_guima Avatar asked Apr 07 '12 19:04

newton_guima


People also ask

How do you find the fractional part of a float?

Using the modulo ( % ) operator The % operator is an arithmetic operator that calculates and returns the remainder after the division of two numbers. If a number is divided by 1, the remainder will be the fractional part. So, using the modulo operator will give the fractional part of a float.

How do you remove the decimal part of a number?

Step 1: Write down the decimal divided by 1. Step 2: Multiply both top and bottom by 10 for every number after the decimal point. (For example, if there are two numbers after the decimal point, then use 100, if there are three then use 1000, etc.) Step 3: Simplify (or reduce) the Rational number.

How do you extract the decimal part of a number in Python?

modf() function is an inbuilt function in Python that returns the fractional and integer parts of the number in a two-item tuple. Both parts have the same sign as the number. The integer part is returned as a float.

How do you get the decimal part of a number in Excel?

Select a cell and type this formula =A1-TRUNC(A1) (A1 is the cell you want to extract decimal value from) into the Formula Bar, and then press Enter key. Keep selecting the first result cell, and drag fill handle down to get all results. You can see the decimal values are extracted with sign as below screenshot shown.


2 Answers

I'm not sure if there is a function doing exactly the way you want but you can use this:

x - floor(x)
like image 52
Thiem Nguyen Avatar answered Sep 22 '22 06:09

Thiem Nguyen


The accepted answer above (x - floor(x)) works for positive numbers but does not the right thing for negative numbers. Use trunc() instead:

x - trunc(x)

But the fmod() solution is the one to use if you ask me:

fmod(x, 1)
like image 29
JKvr Avatar answered Sep 21 '22 06:09

JKvr