Ankit
Ankit

Reputation: 1887

Keep Zero after decimal ( getting removed when adding two double numbers)

print(4.0+4.0);

I want it to output 8.0 instead of 8 . Looks like + discards the useless zero from the output. Any way I can keep it?

Upvotes: 0

Views: 64

Answers (2)

Shaunak Shukla
Shaunak Shukla

Reputation: 2347

You can use number_format() for numeric formation.

For your example:

print(number_format(4.0+4.0,1));

If it is a large number, you can still use it.

e.g. print(number_format(404.0+808.0,1,".",""));

This function automatically rounds the value too.

e.g. print(number_format(4.5+4.46,1,".",""));

Reference

Edit

Another function for sum:

echo bcadd(4.0, 4.0, 1);

Reference

Code Snipet

EDIT - After Comment

$A = 4.44;
$B = 5.56;
$loc = strpos($A,'.')?explode('.',$A):(strpos($B,'.')?explode('.',$B):0);
$len = isset($loc[1])?strlen($loc[1]):0;
print(number_format($A+$B,$len,".",""));

This can be helpful to you!

Upvotes: 1

Jens
Jens

Reputation: 69440

use sprinf to Format the Output or printf:

sprintf("%.0f", 4.0+4.0)

or

printf("%.0f", 4.0+4.0)

For more informations about sprintf see the documentation or prinf documentation.

Upvotes: 0

Related Questions