PHP Scientific Notation Shortening

2019-08-30 00:25发布

I'm looking for an elegant solution here (if one exists).

I've got a bunch of numbers, with an arbitrary amount of decimal places. I want to force the number to use 8 decimal places if it's got more than 8 trailing zeroes i.e.

0.000000004321

That would be converted to:

0.00000001

But I don't want to use number format because if I force it to 8 decimals with number format my numbers without 8 decimal places will look like:

1.00000000

I'd rather these just look like (for amounts >= 1):

1.00700000 -> 1.01

And for amounts < 1:

0.00300000 -> 0.003

If the number is less than 1 i.e. 0.XX I want it to have more precision (up to 8, chopping off all trailing 0's).

So, again, here's a few examples to make it clear:

1.00300000  -> 1.01 (maintain and round 2p for amounts >= 1)
0.00300000  -> 0.003 (maintaining precision, removing trailing 0's for amounts < 1)

1.00300001  -> 0.01 (maintain and round 2dp for amounts >= 1)
0.00300001  -> 0.00300001 (no change needed on this)
0.003000017 -> 0.00300002 (rounds upward to 8dp because it's < 1)

1.000000002 -> 1.00 (maintain and round 2dp for amounts >= 1)
0.000000002 -> 0.00000001 (rounds upward to 8dp because it's < 1)

At the moment my really small numbers are showing in scientific notation too because of the number of decimals. So that's another thing I will need to worry about (i.e. converting out of scientific notation to do the calculations).

I know I can do this with a bunch of generic logic, but it seems like a hacky way of doing things, surely there's some nice solution to this.

Thank you.

1条回答
地球回转人心会变
2楼-- · 2019-08-30 00:51

To round upto 2nd place: ceil()

To remove ending zeros: rtrim()

if($number >= 1)
{
    ceil to 2nd decimal place
}

else //when the number is less than 1
{
    ceil to 8th place
    try rtrim with '0' to remove ending zeros if there is any
}
查看更多
登录 后发表回答