Please help to extract the decimal portion

T

Tharma

Hi

I wanted to extract the decimal portion from a number. I tried the following
code but I didn't get the exact decimal portion.
If anyone know how to extract please let me know.


$num = 1234.56;
$decimal = ($num - int($num));
print $decimal;

Here I get 0.559999999999945 instead of 0.56. Why and How can I correct it?.
 
J

Jürgen Exner

Tharma said:
I wanted to extract the decimal portion from a number. I tried the
following code but I didn't get the exact decimal portion.
If anyone know how to extract please let me know.


$num = 1234.56;
$decimal = ($num - int($num));
print $decimal;

Here I get 0.559999999999945 instead of 0.56. Why and How can I
correct it?.

"Thou shalt not use floating point numbers when accurate results are needed"
You must have missed the introduction into computer numerics, for further
details see "perldoc -q 999".

One way may be to just treat the number as text (untested):
$decimal = 1234.56;
$decimal =~ s/.*\.//;
print $decimal;

jue
 
T

Tharma

thanks.

Jürgen Exner said:
"Thou shalt not use floating point numbers when accurate results are needed"
You must have missed the introduction into computer numerics, for further
details see "perldoc -q 999".

One way may be to just treat the number as text (untested):
$decimal = 1234.56;
$decimal =~ s/.*\.//;
print $decimal;

jue
 
M

magoo

use "sprintf" like so...

$decimal = sprintf("%.2f", ($num - int($num));

magoo

(e-mail address removed) says...
 
M

magoo

Better add one more ")" on the end there! ;>)

magoo@hal- said:
use "sprintf" like so...

$decimal = sprintf("%.2f", ($num - int($num));

magoo

(e-mail address removed) says...
 
S

Skeleton Man

I wanted to extract the decimal portion from a number. I tried the
following
code but I didn't get the exact decimal portion.
If anyone know how to extract please let me know.

$num = 1234.56;
$decimal = ($num - int($num));
print $decimal;

Try this:

$num = 1234.56;
print '.'.@{[split(/\./,$num)]}[1];


Regards,
Chris
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top