Mini
Mini

Reputation: 63

How to round small decimal numbers in php

I have this number:

0.108504578471184

And I would like to round it keeping two decimals, I've tried using the php function round() like this:

round(0.108504578471184, 2)

Expected result:

0.11

Actual Result:

0

Why is it giving me 0 when I've specified that I want 2 decimals? EDIT: As noted in the comments, the problem is something else in the code. I am selecting a xml attribute with this line

$selectedMpoint->xpath('/RFile/Machine/MPoint[@No="'.$MPNo.'"]/Operation[@FrqRange="'.$MPFrqRange.'"]/QParam[@Qid="1"]/@Value')[0];

Echoing the line:

echo $selectedMpoint->xpath('/RFile/Machine/MPoint[@No="'.$MPNo.'"]/Operation[@FrqRange="'.$MPFrqRange.'"]/QParam[@Qid="1"]/@Value')[0];

Gives me this number (same as mentioned before)

0.1085045784711840

But when I try to use round() on it it just gives me 0, I've tried putting it into a variable because I thought that it could be like the [0], 2 at the end messing it up, but i still get 0e

round($selectedMpoint->xpath('/RFile/Machine/MPoint[@No="'.$MPNo.'"]/Operation[@FrqRange="'.$MPFrqRange.'"]/QParam[@Qid="1"]/@Value')[0], 2

Upvotes: 2

Views: 329

Answers (1)

Osama Sayed
Osama Sayed

Reputation: 2023

Although round(0.108504578471184, 2) produces 0.11 for me, but you can try using number_format:

(float) number_format(0.108504578471184, 2);

Upvotes: 1

Related Questions