LoginSignup
0

More than 1 year has passed since last update.

PHPで数値のカンマ区切りプログラムを作成しました。

Last updated at Posted at 2022-06-14

Webアプリケーションで数値のカンマプログラムを作成しました。
ソースコードを公開します。

注) 今回はJavaのFormatter、PHPのnumber_format関数は使用禁止という条件です。

条件を入れ忘れましたので追記いたします。

canma.php(入力側)

<!--   カンマ区切りプログラム -->
<!--   新規作成  2022/06/13-->
<!--   作成者  乃木坂好きのITエンジニア-->
<!DOCTYPE html>
<html lang="ja">

<!--  ヘッダー部分-->    
<head>
    <meta charset="utf-8">
    <title>カンマ区切りプログラム</title>
    <script type="text/javascript"> 
        function check(){
            //変数の定義
            const number = document.getElementById('number');
    
  
            if(number.value.replace(/\s+/, '').length == 0 ){
                alert('数字が入力されていません');
                return false;
            } else {
                if(window.confirm('送信してよろしいですか?')){ // 確認ダイアログを表示

		          return true; // 「OK」時は送信を実行

	           }  else{ // 「キャンセル」時の処理

		          window.alert('キャンセルされました'); // 警告ダイアログを表示
		          return false; // 送信を中止
               }

	       }

        }

    </script>
</head>
    
<!--  ボディー部分-->    
<body>
    <h1>数値入力フォーム</h1>
	<form id = "entry" action="canma_result.php" method="post" role="form" onSubmit="return check()">
        <div class="form-group">
            <dd>数字を入力してください
            <dt> <span class="must"> * </span></dt>     
            <dd> <label>数字記入欄</label></dd>
            <dd> <input type="text" name="number" id="number"></dd>
        </div>
        <p></p>
        <button type="submit" id="submit" >カンマ区切り数字表示</button>
    
	</form>
       
</body>
<footer>
    <small> by 乃木坂好きのITエンジニア</small>
</footer>
</html>

canma_result.php(結果を出力)

<!--   カンマ区切りプログラム -->
<!--   新規作成  2022/06/13-->
<!--   作成者  乃木坂好きのITエンジニア-->
<!DOCTYPE html>
<html lang="ja">

<!--  ヘッダー部分-->    
<head>
    <meta charset="utf-8">
    <title>結果</title>
</head>
    
<!--  ボディー部分-->    
<body>
    <?php
            $data = $_POST['number'];
            $fu_flag = 0;
            if ($data < 0){
                $fu_flag = 1;
                $data = $data * (-1);
            }
            $array = str_split($data);
            $num = count($array);
            $amari = ($num - 1) % 3;
            $str = "";
            for($i=0;$i<$num;$i++){
                $str = $str . $array[$i];
                if(($i % 3 == $amari) && ($num - $i > 1)){
                    $str = $str . ",";
                }
            }
            if ($fu_flag == 1){
                $str = "-" . $str;
            }
            echo "<p>" . $str . "</p>";
            echo "<a href='canma.php'>元に戻る</a>";
    ?>    
       
</body>
<footer>
    <small> by 乃木坂好きのITエンジニア</small>
</footer>
</html>

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0