Home > OS >  Is it possible to separate last digits in Php?
Is it possible to separate last digits in Php?

Time:01-25

I have a string value which size 11(2): 00000700000

I want to convert this string to decimal. I clean leading zeros with ltrim function and then put comma at the end of the value with the function substr_replace:

ltrim(substr_replace( '00000700000', '.', -2, 0), '0')

The expected result is:

7000.00

Are there any cleaner way to separate last two digits with dot and convert this string to decimal?

CodePudding user response:

You can simply cast that string to int and divide by 100:

intval('00000700000') / 100; // 7000

If you want that same number formatted, use format_number():

number_format(num: $result, decimals: 2, thousands_separator: '') // 7000.00

Example

  •  Tags:  
  • php
  • Related