Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to get the fractional part of a float in PHP?

Tags:

php

How would you find the fractional part of a floating point number in PHP?

For example, if I have the value 1.25, I want to return 0.25.

like image 628
tkrehbiel Avatar asked Sep 08 '08 21:09

tkrehbiel


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.

What is the fractional part of a floating point number called?

and with this standard, floating point numbers are represented in the form, s represents the sign of the number. When s=1, floating point number is negative and when s=0 it is positive. F represent the fraction (which is also called mantissa) and E is the exponent.

How do you find the fractional part of a real number?

y=\{x\}. y={x}. For nonnegative real numbers, the fractional part is just the "part of the number after the decimal," e.g. { 3.64 } = 3.64 − ⌊ 3.64 ⌋ = 3.64 − 3 = 0.64.


2 Answers

$x = $x - floor($x) 
like image 55
nlucaroni Avatar answered Oct 01 '22 06:10

nlucaroni


$x = fmod($x, 1); 

Here's a demo:

<?php $x = 25.3333; $x = fmod($x, 1); var_dump($x); 

Should ouptut

double(0.3333) 

Credit.

like image 33
2 revs Avatar answered Oct 01 '22 05:10

2 revs