-2

I have this code :

<?php

$number = 0.000010950000;
$number = number_format($number, 10, '.', '');
$number = $number + 0;

echo $number;

I'm expecting this as result :

0.00001095

but, by using number_format only, it will produce :

0.0000109500

and by adding + 0 to remove unnecessary zero, it will print the number into scientific format :

1.095E-5

how to keep the result in decimal format and remove unnecessary zero?

please note, length of number can be vary.

Saint Robson
  • 5,475
  • 18
  • 71
  • 118
  • 1
    As an option, store as is, but use `rtrim($number, '0')` before output. – Marat Tanalin May 17 '19 at 17:04
  • 1
    @MaratTanalin : I used rtrim before. but if you have number like 10.00, you will get 10. (with extra dot). any idea how to get 10 (without dot)? – Saint Robson May 17 '19 at 17:07
  • 1
    Possible duplicate of [PHP Remove Unnecessary Zero In Decimals Works, But Not With This Number](https://stackoverflow.com/questions/56172607/php-remove-unnecessary-zero-in-decimals-works-but-not-with-this-number) – Andreas May 17 '19 at 17:17
  • @MaratTanalin's comment perfectly fits the issue *as you have described it in your question*. If there are extra situations that need to be covered (as described in your comment) please update (**edit**) your question to clarify these additional circumstances. I have included a solution your comments in my answer to your question. Thank you. – Martin May 17 '19 at 17:32
  • @Andreas this is a useless duplicate. that question has no answers. And it's own dupe-trail goes back to a question whose answers do not fit this situation. – Martin May 17 '19 at 17:43
  • The thing is I wanted to show that the user has asked the same question in the past and didn't even answer what output he/she wanted – Andreas May 17 '19 at 17:47
  • @Andreas that is a fair point but it is still not a useful duplicate flag. Maybe one eventually for a moderator to tag as a repetative asking.... – Martin May 17 '19 at 17:52
  • Possible duplicate of [Remove useless zero digits from decimals in PHP](https://stackoverflow.com/questions/14531679/remove-useless-zero-digits-from-decimals-in-php) – revo May 17 '19 at 17:55

1 Answers1

2

From comments:

$number = 0.000010950000;
$number = number_format($number, 10, '.',''); // to avoid scientific notation of tiny decimals
$number = rtrim((string)$number,'0');
$number = rtrim((string)$number,'.');

echo $number; 

What this does:

the first rtrim will clear the excess 0, the second rtrim will clear any trailing . after the first rtrim is completed.

Why not combine the rtrims together (rtrim($number, '0.'))?

This will cause 10.0000 to become 1 which is obviously incorrect.

Examples:

$number = 0.000010950000;

output: $number = 0.00001095

and

$number = 10.000000;

output: $number = 10

Martin
  • 22,212
  • 11
  • 70
  • 132