0

I have number from database where the column type is set to string. I have no control of the database since I am just consuming it as an api. What I need is to convert and format it according to its decimal values(not count)

So

37.2348 should be 37.24

What I tried

number_format(37.2348, 2) -> 37.23
round(37.2348, 2) -> 37.23

There's no need to convert the result from string to decimal, as I noticed the Php built in number_format function can automatically convert and format it. Any Ideas ?

ira
  • 534
  • 1
  • 5
  • 17
  • 1
    Why would 37.2348 round to 37.24? – Alex Howansky Nov 25 '21 at 01:11
  • If you are trying to round up, use [`ceil()`](https://www.php.net/manual/en/function.ceil.php). – Skully Nov 25 '21 at 01:12
  • 1
    Don't be presumptuous, I did not downvote. Please explain how you arrive at your desired result, as it is not standard rounding. E.g., what would 37.2300001 round to? – Alex Howansky Nov 25 '21 at 01:14
  • @Skully that would result in 38 – ira Nov 25 '21 at 01:18
  • @ira See [this answer](https://stackoverflow.com/a/48456940/8982034) for a function posted by user Mojo that may work for you. – Skully Nov 25 '21 at 01:26
  • I end up using this function private static function round_up ( $value, $precision ) { $pow = pow ( 10, $precision ); return ( ceil ( $pow * $value ) + ceil ( $pow * $value - ceil ( $pow * $value ) ) ) / $pow; } to get my desired result – ira Nov 25 '21 at 01:35

0 Answers0