Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a fraction from a float number?

I have a floating point number:

var f = 0.1457; 

Or:

var f = 4.7005 

How do I get just the fraction remainder as integer?

I.e. in the first example I want to get:

var remainder = 1457; 

In the second example:

var remainder = 7005; 
like image 482
Richard Knop Avatar asked Jan 12 '11 09:01

Richard Knop


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 find the fractional part of a number in Python?

Python math function | modf() 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.


2 Answers

function frac(f) {     return f % 1; } 

hope that helps ;-)

like image 68
Martina Avatar answered Oct 02 '22 12:10

Martina


While this is not what most people will want, but TS asked for fract as integer, here it is:

function fract(n){ return Number(String(n).split('.')[1] || 0); } fract(1.23) // = 23 fract(123) // = 0 fract(0.0008) // = 8 
like image 43
metalim Avatar answered Oct 02 '22 13:10

metalim