简体   繁体   中英

convert string in indian format in javascript

I need to convert a string(which is a number input from the UI) in Indian format in javascript/jquery only

Input: 1234567
Output: 12,34,567

Input: 91234567.00
Output: 9,12,34,567.00

I have written the same in java but struggling to write it in javascript

For your reference, Java code is below

public static String indianFormat(BigDecimal n) {
    DecimalFormat formatter = new DecimalFormat("##,###");
    boolean negFlag = n.compareTo(BigDecimal.ZERO) < 0 ? true : false;
    n = n.abs();
    String dec = "";
    if (n.toString().indexOf(".") > -1) {
        dec = "." + n.setScale(2, RoundingMode.HALF_UP).toString().split("\\.")[1];
    } else {
        dec = ".00";
    }
    String returnValue = "";

    if (n.longValue() > 9999) {
        formatter.applyPattern("#,##");

        returnValue = formatter.format((int) (n.longValue() / 1000)) + ",";
        formatter.applyPattern("#,###");
        String rem = formatter.format(n.longValue() - (long) (n.longValue() / 1000) * 1000);
        if (Integer.parseInt(rem) == 0) {
            returnValue = returnValue + "000";
        } else if (Integer.parseInt(rem) < 10) {
            returnValue = returnValue + "00" + rem;
        } else if (Integer.parseInt(rem) < 100) {
            returnValue = returnValue + "0" + rem;
        } else {
            returnValue = returnValue +  rem;
        }

    } else if (n.intValue() >= 1000 && n.intValue() <= 9999) {
        formatter.applyPattern("#,###");

        returnValue = formatter.format(n.intValue());

    } else {

        returnValue += n.intValue();

    }

    if (negFlag == true)
        return "-" + returnValue + dec;
    else
        return returnValue + dec;

}

You may want to try jQuery Globalize :

https://github.com/jquery/globalize#number-formatting

The culture "te-IN" does exactly that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM