Skip to content
Advertisement

Remove useless zero digits from decimals and remove decimals above 2 in PHP

I’m trying to find a fast way to first make my number 2 decimals only and then remove zero decimals from result values like this:

JavaScript

I tried number format but when I call it with 0 it acts like this:

JavaScript

But I want 0

Does there exist some optimized way to do that?

Advertisement

Answer

There are probably better ways to achieve this, but the first approach that springs to mind is simply trimming it away using rtrim() with .0 as the trim. This will however also trim entirely away when you have cases like 0.00 (and just return an empty string), so we can perform an explicit check for that.

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement