Fancy Amount? :/

Nggak tau juga ini namanya apa :/ Saya sebut aja fancy amount.

Jadi ceritanya mau bikin format harga seperti yang ada di Traveloka. Tiga digit dibelakangnya jadi kecil.

Screen Shot 2014-12-28 at 11.34.53

Gak yakin ini codenya efektif dan optimal. At least it works

Kalo mau liat demo di CodePen http://codepen.io/mul14/pen/jEMpmP/

function fancyAmount(numbers) {

  var numbers = String(numbers);

  var small = numbers.substr(numbers.length -3)
                     .replace(/(.+)/, "<small>$1</small>");

  return numbers.replace(/(d)(?=(d{3})+(?!d))/g, '$1.')
                .replace(/(d{0,3}$)/, small);
}

Kalo ingat dan ada waktu, nanti di-optimize. 😀
Atau kalo ada yang mau bantu, silahkan

UPDATE siangnya

Coba implementasikan di AngularJS. Tinggal jadiin filter. Misalnya

angular.module('App', [])
  // ... other code
  .filter('fancyAmount', function ($sce) {
    return function (numbers) {

       var numbers = String(numbers);

       var front = numbers.replace(/(d)(?=(d{3})+(?!d))/g, '$1.')

       var small = numbers.substr(numbers.length - 3)
                          .replace(/(.+)/, "<small>.$1</small>");

       var finalle = front.replace(/(.d{3}$)/, small);

       return $sce.trustAsHtml(finalle);
    }
  });

Lalu di HTML

...
<span ng-bind-html="123456789 | fancyAmount"></span>

Kenapa pake ng-bind-html dan $sce? :/
Karena kalau langsung, tag <small> akan di-escape.

Dengan sedikit bumbu CSS, outputnya jadi seperti ini 😀

Screen Shot 2014-12-28 at 14.33.21

Iklan

Tinggalkan Balasan

Please log in using one of these methods to post your comment:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout / Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout / Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout / Ubah )

Foto Google+

You are commenting using your Google+ account. Logout / Ubah )

Connecting to %s