Skip to content

Instantly share code, notes, and snippets.

@mohsin
Created May 10, 2017 12:26
Show Gist options
  • Select an option

  • Save mohsin/0ae423e57ced58f390ee234486c7135a to your computer and use it in GitHub Desktop.

Select an option

Save mohsin/0ae423e57ced58f390ee234486c7135a to your computer and use it in GitHub Desktop.
Java Class to convert a number to a short-format indian currency representation
import java.util.*;
import java.util.Map.*;
import java.text.DecimalFormat;
/**
* Makes a longer number shorter like cr., lac, etc.
* Output: 500, 4k, 30k, 99k, 2lac, 9.9lac, 40lac, 99lac, 1.9Cr., 20Cr., 100Cr., 214Cr
* Limitation: Works from zero to the longest int or as Indians call, the Mallya limit.
*/
public class InrSimplifier {
private static final NavigableMap<Long, String> suffixes = new TreeMap<> ();
static {
suffixes.put(1_000L, "k");
suffixes.put(1_00_000L, "lac");
suffixes.put(1_00_00_000L, "Cr.");
}
public static void main(String[] args) {
System.out.println(InrSimplifier.format(500));
System.out.println(InrSimplifier.format(4000));
System.out.println(InrSimplifier.format(30000));
System.out.println(InrSimplifier.format(99999));
System.out.println(InrSimplifier.format(200000));
System.out.println(InrSimplifier.format(999999));
System.out.println(InrSimplifier.format(4000000));
System.out.println(InrSimplifier.format(9999999));
System.out.println(InrSimplifier.format(19999999));
System.out.println(InrSimplifier.format(209999999));
System.out.println(InrSimplifier.format(1009999999));
System.out.println(InrSimplifier.format(2147483647)); // <-- Largest Int
}
public static String format(long value) {
//Long.MIN_VALUE == -Long.MIN_VALUE so we need an adjustment here
if (value == Long.MIN_VALUE) return format(Long.MIN_VALUE + 1);
if (value < 0) return "-" + format(-value);
if (value < 1000) return Long.toString(value); //deal with easy case
Entry<Long, String> e = suffixes.floorEntry(value);
Long divideBy = e.getKey();
String suffix = e.getValue();
long truncated = value / (divideBy / 10); //the number part of the output times 10
boolean hasDecimal = truncated < 100 && (truncated / 10d) != (truncated / 10);
return hasDecimal ? (truncated / 10d) + suffix : (truncated / 10) + suffix;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment