I have an integer of specific length (I know it will have 14 digits, no more, no less), for example:
98000011601815
I want to format it to a string, so it looks like this:
9800-0011-6018-15
How can I do this properly? I know I can do this with using a lot of substr(), but I think there's a more elegant way that I'm not familiar with.
My Answer:
You can achieve this formatting using the number_format() function in PHP. Here's an example code snippet to format the number as per your requirement:
php
$number = 98000011601815;
$formatted_number = number_format($number, 0, '', '-');
echo $formatted_number; // Output: 9800-0011-6018-15
In the number_format() function:
- The first parameter is the number you want to format.
- The second parameter is the number of decimal points. Since you don't want any decimal points, it is set to 0.
- The third parameter is the decimal separator. Since you don't want any separator, it is set to an empty string.
- The fourth parameter is the thousands separator. In this case, you want to use a hyphen as the separator.
This will give you the desired output without having to use multiple substr() functions.
Rate this post
3 of 5 based on 1252 votesComments