Home > database >  How to Format Input as Currency and Save as Integer in Laravel?
How to Format Input as Currency and Save as Integer in Laravel?

Time:01-06

enter image description here

Good night from Indonesia, help me, please. i am creating an input display with currency format but when i save it, the input data is 0. What is the correct way to format the currency input and save it as an integer ? the following is the code that I have made.

Blade

<div >
   <label ><b>Harga</b></label>
   <input type="text" name="harga" id="harga"  placeholder="Masukkan Harga" />
</div>
<script>
var harga = document.getElementById('harga');
harga.addEventListener('keyup', function(e)
{
    harga.value = formatRupiah(this.value, 'Rp. ');
});

function formatRupiah(angka, prefix)
{
    var number_string = angka.replace(/[^,\d]/g, '').toString(),
        split    = number_string.split(','),
        sisa     = split[0].length % 3,
        rupiah     = split[0].substr(0, sisa),
        ribuan     = split[0].substr(sisa).match(/\d{3}/gi);
        
    if (ribuan) {
        separator = sisa ? '.' : '';
        rupiah  = separator   ribuan.join('.');
    }
    
    rupiah = split[1] != undefined ? rupiah   ','   split[1] : rupiah;
    return prefix == undefined ? rupiah : (rupiah ? 'Rp. '   rupiah : '');
}
</script>

Controller

    public function tambahScript(Request $request)
    {
        try{
            $img = $request['photo'];
            if (!$img == null) {
                $filename = time() . $img->getClientOriginalExtension();
                $img->storeAs('/photoScript', $filename, 'photoScript');
            } else {
                $filename = "blank.png";
            }

            $impld = implode("," ,$request->input('payment_id'));

            $script = Script::create([
                'user_id' => $request->user_id,
                'script_name' => $request->script_name,
                'product_name' => $request->product_name,
                'market_target' => $request->market_target,
                'payment_id' => $impld,
                'photo' =>$filename,
                'category' => $request->category,
                'harga' => $request->harga
            ]);   
            return response()->json([
                'status' => '200',
                'message' => 'Success add script',
                'data' => $script,
            ], 200);
        }catch(Exception $err){
            return response()->json([
                'status' => '500',
                'error' => $err->getMessage()
            ], 500);
        }
    }

Thank you

CodePudding user response:

Other things are pretty on, you just need to remove Rp. from input field, you can put it into an addon,

<div >
   <label ><b>Harga</b></label>
   <div >
      <span >Rp.</span>
       <input type="text" name="harga" id="harga"  placeholder="Masukkan Harga" />
   </div>
</div>

And the other thing you can do is change your amount field (e.g harga) from Integer to Decimal so you can store decimal values too. Integer will hold full digits only, that in 200, with Decimal you can store 200.00, 200.52 etc.

and if you are using . DOT as thousand separator then there is no need to change your amount field (e.g harga) from Integer to Decimal just replace . in Script::create.

$script = Script::create([
    'user_id' => $request->user_id,
    'script_name' => $request->script_name,
    'product_name' => $request->product_name,
    'market_target' => $request->market_target,
    'payment_id' => $impld,
    'photo' =>$filename,
    'category' => $request->category,
    'harga' => str_replace('.','',$request->harga)
]); 

CodePudding user response:

You could use a hidden field or a variable to store the actual value in. That's something you'd find in some frameworks:

var formatInput = document.getElementById('js-format-input')
var hargaValue = ''

function renderInput() {
    var template = `<div >
   <label ><b>Harga</b></label>
   <input type="hidden" name="harga" id="harga"  placeholder="Masukkan Harga" value="${ hargaValue}" />
   <input type="text" name="harga_format" id="harga_format"  placeholder="Masukkan Harga" value="${formatRupiah(hargaValue, 'Rp. ')}" autofocus />
</div>`
  formatInput.innerHTML = template
  var harga = document.getElementById('harga');
  var hargaFormatted = document.getElementById('harga_format');
  hargaFormatted.addEventListener('keyup', function(e)
  {
      hargaValue = this.value.replace('Rp. ', '')
      renderInput();
  });
  hargaFormatted.focus()
  PosEnd(hargaFormatted)
}

function formatRupiah(angka, prefix)
{
    var number_string = angka.replace(/[^,\d]/g, '').toString(),
        split    = number_string.split(','),
        sisa     = split[0].length % 3,
        rupiah     = split[0].substr(0, sisa),
        ribuan     = split[0].substr(sisa).match(/\d{3}/gi);
        
    if (ribuan) {
        separator = sisa ? '.' : '';
        rupiah  = separator   ribuan.join('.');
    }
    
    rupiah = split[1] != undefined ? rupiah   ','   split[1] : rupiah;
    return prefix == undefined ? rupiah : (rupiah ? 'Rp. '   rupiah : '');
}        function PosEnd(end) {
            var len = end.value.length;
              
            // Mostly for Web Browsers
            if (end.setSelectionRange) {
                end.focus();
                end.setSelectionRange(len, len);
            } else if (end.createTextRange) {
                var t = end.createTextRange();
                t.collapse(true);
                t.moveEnd('character', len);
                t.moveStart('character', len);
                t.select();
            }
        }

renderInput();
<form>
  <div id="js-format-input"></div>
</form>

  •  Tags:  
  • Related