code_junkie

Whats the cleanest way to convert a 5-7 digit number into xxx/xxx/xxx format in php?

Nov 11th, 2011
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.58 KB | None | 0 0
  1. function formatMyNumber($num)
  2. {
  3. return sprintf('%03d/%03d/%03d',
  4. $num / 1000000,
  5. ($num / 1000) % 1000,
  6. $num % 1000);
  7. }
  8.  
  9. $padded = str_pad($number, 9, '0', STR_PAD_LEFT);
  10. $split = str_split($padded, 3);
  11. $formatted = implode('/', $split);
  12.  
  13. function FormatWithSlashes($number)
  14. {
  15. return substr(preg_replace('/(d{3})?(d{3})?(d{3})$/', '$1/$2/$3',
  16. '0000' . $number),
  17. -11, 11);
  18. }
  19.  
  20. $numbers = Array(12345, 345678, 9876543);
  21. foreach ($numbers as $val)
  22. {
  23. $r = FormatWithSlashes($val);
  24. echo "<p>$r</p>";
  25. }
  26.  
  27. function fmt($x) {
  28. return substr(number_format($x+1000000000, 0, ".", "/"), 2);
  29. }
  30.  
  31. function FormatWithSlashes($number)
  32. {
  33. return preg_replace('/^0*(d{3})(d{3})(d{3})$/', '$1/$2/$3',
  34. '0000' . $number);
  35. }
  36.  
  37. substr('0000' . $number, -9, 9);
  38.  
  39. use 5.010;
  40.  
  41. sub myformat(_;$){
  42.  
  43. # prepend with zeros
  44. my $_ = 0 x ( 9-length($_[0]) ) . $_[0];
  45.  
  46. my $join = $_[1] // '/'; # using the 'defined or' operator `//`
  47.  
  48. # m// in a list context returns ($1,$2,$3,...)
  49. join $join, m/ ^ (d{3}) (d{3}) (d{3}) $ /x;
  50.  
  51. }
  52.  
  53. $_ = 11111;
  54. say myformat;
  55. say myformat(2222);
  56. say myformat(33333,';');
  57. say $_;
  58.  
  59. Perl 5.8
  60.  
  61. sub myformat(;$$){
  62. local $_ = @_ ? $_[0] : $_
  63.  
  64. # prepend with zeros
  65. $_ = 0 x ( 9-length($_) ) . $_;
  66.  
  67. my $join = defined($_[1]) ? $_[1] :'/';
  68.  
  69. # m// in a list context returns ($1,$2,$3,...)
  70. join $join, m/ ^ (d{3}) (d{3}) (d{3}) $ /x;
  71.  
  72. }
  73.  
  74. def convert(num): #num is an integer
  75. a = str(num)
  76. s = "0"*(9-len(a)) + a
  77. return "%s/%s/%s" % (s[:3], s[3:6], s[6:9])
Add Comment
Please, Sign In to add comment