Skip to content

Instantly share code, notes, and snippets.

@mramirid
Forked from faisalman/Rupiah.as
Last active January 7, 2023 02:11
Show Gist options
  • Save mramirid/56e316e907ec6191e16d3a2d1927dfbe to your computer and use it in GitHub Desktop.
Save mramirid/56e316e907ec6191e16d3a2d1927dfbe to your computer and use it in GitHub Desktop.
Convert a number to a string of its equivalent in rupiah (TypeScript)
// JavaScript Code Snippet
// Convert integer to Rupiah & vice versa
// https://gist.github.com/845309
//
// Copyright 2011-2012, Faisalman
// Licensed under The MIT License
// http://www.opensource.org/licenses/mit-license
/**
* Convert a number to a string of its equivalent in rupiah
* @param {number} nominal - The number to be converted to rupiah.
*/
export function convertToRupiah(nominal: number) {
if (nominal === 0) return "Rp. 0";
if (!nominal.toString().match(/^\d+$/)) {
throw new Error("Nominal must be an integer");
}
let rupiah = "";
const reversedNominal = nominal.toString().split("").reverse().join("");
for (let i = 0; i < reversedNominal.length; i++) {
if (i % 3 === 0) {
rupiah += reversedNominal.substr(i, 3) + ".";
}
}
return (
"Rp. " +
rupiah
.split("", rupiah.length - 1)
.reverse()
.join("")
);
}
/**
* Convert a string of rupiah to a number
* @param {string} rupiah - the string that contains the rupiah amount
* @returns a number.
*/
export function convertRupiahToNumber(rupiah: string) {
return parseInt(rupiah.replace(/,.*|[^0-9]/g, ""), 10);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment