Advertisement
sohotcall

PHP Terbilang (Nonrekursif) dan Roman

Jan 6th, 2021
1,120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.89 KB | None | 0 0
  1. <?php
  2. //PHP Terbilang (Nonrekursif) dan Roman
  3. static function terbilang( $x, $mode = 2, $cent = 0 ){
  4.     $x = number_format( $x, $cent, ".", "," );
  5.     list( $x, $y ) = explode( ".", $x . "." );
  6.     $satuan = array( "Nol", "Satu", "Dua", "Tiga", "Empat", "Lima", "Enam", "Tujuh", "Delapan", "Sembilan" );
  7.     $ribuan = array( 1 => "Ribu", "Juta", "Miliar", "Triliun" );
  8.     foreach ( array_reverse( explode( ",", $x ) ) as $k => $v ){
  9.         if ( $v == 0 ){
  10.             if ( $x == 0 )
  11.                 $result[$k] = "Nol";
  12.         } elseif ( $k * $v == 1 ){
  13.             $result[$k] = "Seribu ";
  14.         } elseif ( $v ){
  15.             $tigaan = str_split( substr( 1000 + $v, -3 ) );
  16.             if ( $tigaan[0] == 1 )
  17.                 $result[$k] = "Seratus ";
  18.             elseif ( $tigaan[0] )
  19.                 $result[$k] = $satuan[$tigaan[0]] . " Ratus ";
  20.             if ( $tigaan[1] == 1 && $tigaan[2] == 0 )
  21.                 $result[$k] .= "Sepuluh ";
  22.             elseif ( $tigaan[1] == 1 && $tigaan[2] == 1 )
  23.                 $result[$k] .= "Sebelas ";
  24.             elseif ( $tigaan[1] == 1 )
  25.                 $result[$k] .= $satuan[$tigaan[2]] . " Belas ";
  26.             else {
  27.                 if ( $tigaan[1] )
  28.                     $result[$k] .= $satuan[$tigaan[1]] . " Puluh ";
  29.                 if ( $tigaan[2] )
  30.                     $result[$k] .= $satuan[$tigaan[2]] . " ";
  31.             }
  32.             if ( $k )
  33.                 $result[$k] .= $ribuan[ $k ] . " ";
  34.         }
  35.     }
  36.     $title = trim( implode( array_reverse( $result ) ) );
  37.     if ( 1 * $y ){
  38.         $title .= " Koma " . $satuan[$y[0]] . " " . $satuan[$y[1]];
  39.     }
  40.     if ( $mode == 0 )
  41.         return strtolower( $title );
  42.     elseif ( $mode == 1 )
  43.         return ucfirst( strtolower( $title ) );
  44.     elseif ( $mode == 2 )
  45.         return ucwords( $title );
  46.     elseif ( $mode == 3 )
  47.         return strtoupper( $title );
  48. }
  49.  
  50. static function roman($x){
  51.     $romans = array( 1000 => 'M', 900 => 'CM', 500 => 'D', 400 => 'CD',
  52.         100 => 'C', 90 => 'XC', 50 => 'L', 40 => 'XL', 10 => 'X',
  53.         9 => 'IX', 5 => 'V', 4 => 'IV', 1 => 'I' );
  54.     $out = "";
  55.     foreach ( $romans as $k=>$v )
  56.         while ( $k <= $x ){
  57.             $out .= $v;
  58.             $x -= $k;
  59.         }
  60.     return $out;
  61. }
  62.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement