Skip to content

Instantly share code, notes, and snippets.

@yanwarrior
Created August 18, 2016 21:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save yanwarrior/77757781515110909c1077c914f26819 to your computer and use it in GitHub Desktop.
Save yanwarrior/77757781515110909c1077c914f26819 to your computer and use it in GitHub Desktop.
Format rupiah di Python
# rupiah.py
# ---------------

import locale

def rupiah_format(angka, with_prefix=False, desimal=2):
    locale.setlocale(locale.LC_NUMERIC, 'IND')
    rupiah = locale.format("%.*f", (desimal, angka), True)
    if with_prefix:
        return "Rp. {}".format(rupiah)
    return rupiah

Running

>>> import rupiah
>>> rupiah.rupiah_format(10000)
'10.000,00'
>>> rupiah.rupiah_format(10000, True)
'Rp. 10.000,00'
@nold2
Copy link

nold2 commented Apr 20, 2020

For others who are not using IND locale

# assume value is a decimal
def transform_to_rupiah_format(value):
    str_value = str(value)
    separate_decimal = str_value.split(".")
    after_decimal = separate_decimal[0]
    before_decimal = separate_decimal[1]

    reverse = after_decimal[::-1]
    temp_reverse_value = ""

    for index, val in enumerate(reverse):
        if (index + 1) % 3 == 0 and index + 1 != len(reverse):
            temp_reverse_value = temp_reverse_value + val + "."
        else:
            temp_reverse_value = temp_reverse_value + val

    temp_result = temp_reverse_value[::-1]

    return "Rp " + temp_result + "," + before_decimal

Run

>>> transform_to_rupiah_format(Decimal(1000.00))
'Rp 1.000,00'

>>> transform_to_rupiah_format(Decimal(10000.00))
'Rp 10.000,00'

@yanwarrior
Copy link
Author

owh,, yeah... thanks brother... you complete what is lacking...

@hakimamarullah
Copy link

Terima kasih, sangat membantu

@dhanipro
Copy link

dhanipro commented Jan 25, 2022

def rupiah_format(angka, with_prefix=False, desimal=2):
    if not angka:
        return 0
    rupiah = "{:,.2f}".format(angka)
    rupiah = rupiah.replace(",", ".")
    if with_prefix:
        return f"Rp{rupiah}"
    return rupiah

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment