以印度编号格式显示货币

我有一个关于格式化卢比货币(印度卢比-INR)的问题。

通常像 450500这样的值被格式化并显示为 450,500。在印度,同样的值显示为 4,50,500

例如,这里的数字表示为:

1
10
100
1,000
10,000
1,00,000
10,00,000
1,00,00,000
10,00,00,000

请参阅 印度编号系统

分隔符位于两位数字之后,除了最后一组数字以千为单位。

我在互联网上搜索,人们要求使用地区 en_GB或模式 #,##,##,##,##0.00

我使用以下标记在 JSTL 上尝试了这种方法:

<fmt:formatNumber value="${product.price}" type="currency"
pattern="#,##,##,##,###.00"/>

但这似乎并没有解决问题。

124484 次浏览

不幸的是,在标准 JavaSEDecimalFormat上不支持可变宽度组。所以它永远不会像你想的那样格式化值:

如果您提供具有多个分组字符的模式,则最后一个字符与整数结束之间的间隔是所使用的间隔。所以 "#,##,###,####" == "######,####" == "##,####,####"

Java 中的大多数数字格式化机制都基于该类,因此继承了这个缺陷。

ICU4J (Java 版的 Unicode 的国际组件)提供了一个 NumberFormat类,是的支持这种格式:

Format format = com.ibm.icu.text.NumberFormat.getCurrencyInstance(new Locale("en", "in"));
System.out.println(format.format(new BigDecimal("100000000")));

这段代码将产生以下输出:

Rs 10,00,00,000.00

Note: the com.ibm.icu.text.NumberFormat class does not extend the java.text.NumberFormat class (because it already extends an ICU-internal base class), it does however extend the java.text.Format class, which has the format(Object) method.

Note that the Android version of java.text.DecimalFormat class is implemented using ICU under the hood and does support the feature in the same way that the ICU class itself does (even though the summary incorrectly mentions that it's not supported).

你可以做一件简单的事,

 float amount = 100000;


NumberFormat formatter = NumberFormat.getCurrencyInstance(new Locale("en", "IN"));


String moneyString = formatter.format(amount);


System.out.println(moneyString);

输出将是 RS 100.000.00。

对于 Android 来说,这对我很有用:

new DecimalFormat("##,##,##0").format(amount);

450500被格式化为450500

Http://developer.android.com/reference/java/text/DecimalFormat.html -DecimalFormat 支持两种分组大小——主分组大小和用于所有其他分组的大小。

我也遇到了同样的问题。 我在 DecimalFormat工作。

我没有 JSTL的知识,但你可以通过我的解决方案找出一些东西。

因此,在 DecimalFormat中分组大小保持不变。我将两部分分开,用不同的模式将它们格式化,并将它们连接起来。这是密码。

public static String format(double value) {
if(value < 1000) {
return format("###", value);
} else {
double hundreds = value % 1000;
int other = (int) (value / 1000);
return format(",##", other) + ',' + format("000", hundreds);
}
}


private static String format(String pattern, Object value) {
return new DecimalFormat(pattern).format(value);
}

它将提供类似印度编码系统的格式。

如果需要小数点,只需在这两种情况下添加 ".##"

"###""###.##""000""000.##"

现有库中的默认方法只能显示数千个分隔符。所以我们需要为此编写自定义函数。您可以使用多个子字符串操作来获得所需的结果。

在爪哇,

function indianCurrencyNumberFormat(rupee) {
string explore_remaining_units = "";
if (rupee.length() > 3) {
last_three_digits = rupee.substring((rupee.length()-3), rupee.length());
remaining_units = rupee.substring(0, (rupee.length()-3));
remaining_units =  ((remaining_units.length()) % 2 == 1) ? "0"+remaining_units : remaining_units;
split_rupee = remaining_units.split("(?<=^(.{2})+)")
for (i = 0; i < sizeof(split_rupee); i++) {
explore_remaining_units += ((i == 0) ? ( (int) split_rupee[i]+"," ) : ( split_rupee[i]+"," ));
}
formatted_rupee = explore_remaining_units+last_three_digits;
} else {
formatted_rupee = rupee;
}
return formatted_rupee;
}

在 php 中:

function indianCurrencyNumberFormat($rupee) {
$explore_remaining_units = "";
if (strlen($rupee) > 3) {
$last_three_digits = substr($rupee, strlen($rupee) - 3, strlen($rupee));
$remaining_units = substr($rupee, 0, strlen($rupee) - 3);
$remaining_units = (strlen($remaining_units) % 2 == 1) ? "0".$remaining_units : $remaining_units;
$split_rupee = str_split($remaining_units, 2);
for ($i = 0; $i < sizeof($split_rupee); $i++) {
$explore_remaining_units .= (($i == 0) ? ( (int) $split_rupee[$i] . "," ) : ( $split_rupee[$i] . "," ));
}
$formatted_rupee = $explore_remaining_units.$last_three_digits;
} else {
$formatted_rupee = $rupee;
}
return $formatted_rupee;
}

你可以看到更多的细节 给你

enter image description here

只需复制过去这个函数。 :)

  public static String rupeeFormat(String value){
value=value.replace(",","");
char lastDigit=value.charAt(value.length()-1);
String result = "";
int len = value.length()-1;
int nDigits = 0;


for (int i = len - 1; i >= 0; i--)
{
result = value.charAt(i) + result;
nDigits++;
if (((nDigits % 2) == 0) && (i > 0))
{
result = "," + result;
}
}
return (result+lastDigit);
}

简单的解决办法是-

Double amount = 5356673553123.0; //amount is an example ,can be used with any double value


**DecimalFormat IndianCurrencyFormat = new DecimalFormat("##,##,###.00");**

那就用来..

String formattedAmount = IndianCurrencyFormat.format(amount);
import java.util.*;


public class string1 {


public static void main(String args[])
{
int i,j;
boolean op=false;


StringBuffer sbuffer = new StringBuffer();
Scanner input = new Scanner(System.in);
System.out.println("Enter a string");
sbuffer.append(input.nextLine());


int length=sbuffer.length();
if(sbuffer.length()<3)
{
System.out.println("string="+sbuffer);
}
else
{
for ( i = sbuffer.length(); i >0; i--)
{


if (i==length-3)
{
sbuffer.insert(i, ",");
op=true;
}
while(i>1 && op==true)
{
i=i-2;


if(i>=1)
{


sbuffer.insert(i, ",");
}
}
}


}
System.out.println("string="+sbuffer);
}
}
//Input:
long num = 450500;


// Unlike other countries, there is no direct Locale field for India.Therefore, we need to construct a locale for India.
Locale loc = new Locale("en", "in"); // This will display currency with "Rs." symbol.


// or use below to display currency with "INR" symbol.
Locale loc = new Locale("", "in");


NumberFormat indiacurrency = NumberFormat.getCurrencyInstance(loc);
String result = indiacurrency.format(num);
System.out.print(result);

这是更好的答案,并动态工作,而不是在代码中手动指定单个语言环境。

public String convertToDefaultCurrencyFormat(String amountToConvert){
NumberFormat formatter = NumberFormat.getCurrencyInstance(Locale.getDefault());
String moneyString = formatter.format(Double.valueOf(amountToConvert));
return moneyString;
}

返回文章页面印度卢比格式改变译者:

选择 English(India)

产出:

₹10,00,000 (Starting with Indian Rupee symbol)
public String getIndianCurrencyFormat(String amount) {
StringBuilder stringBuilder = new StringBuilder();
char amountArray[] = amount.toCharArray();
int a = 0, b = 0;
for (int i = amountArray.length - 1; i >= 0; i--) {
if (a < 3) {
stringBuilder.append(amountArray[i]);
a++;
} else if (b < 2) {
if (b == 0) {
stringBuilder.append(",");
stringBuilder.append(amountArray[i]);
b++;
} else {
stringBuilder.append(amountArray[i]);
b = 0;
}
}
}
return stringBuilder.reverse().toString();
}

这是我所做的,为了得到印度货币格式。如果输入是1234567890意味着输出是1,23,45,67,890。

ALTER 函数[ dbo ] . [ udf _ CurrencyFormat ](@UC varchar (50))返回 作为 BEGIN 声明@FC varchar (50) ,@Scale varchar (3) ,@i Bigint = 1,@a int = 3,@b int = 2,@WhileLlength bigint,@UCScale varchar (50) , @ Con varchar (20) set@Scale = charindex (’.’,@UC)—— if number has’ 如果(@Scale! =’0’)开始设置,则值 else’0’ @ Con = substring (@UCScale,charindex (’.’,@UCScale) ,3) set @ UC = substring (@UC,0,charindex (’.’,@UC))—— substring end If (cast (len (@UC) as bigint)% 2! = 0)-if odd start set @ WhileLlength = (cast (len (@UC) as bigint)-3)/2 while (@i < =@WhileLlength)—— 如果长度为9(cast (len (@UC) as bigint)-3)/2开始设置,则 length-3/2 = 3 @ a = 3 *@i set@UC = stuff (@UC,@a,0,’,’) set@i =@i + 1 end —— while set @ FC =@UC end ——如果奇数比例’0’else 如果(cast (len (@UC) as bigint)% 2 = 0) —— if even start set@WhileLlength = (((cast (len (@UC) as bigint)-1)-3)/2) + 1 while (@i < =@WhileLlength) start if (@i = 1) start set @ UC = stuff (@UC,@b,0,’,’) end else start set@b =@b + 3 set @ UC = stuff (@UC,@b,0,’,’) end set@i =@i + 1 end set@FC =@UC end 如果(@Scale! =’0’)开始设置@FC =@FC +@Con end ——如果(@Scale! =’0’)——设置 @ FC =@UC return@FC END

如果没有可用的默认区域设置,并且用户不对区域设置进行任何更改,我们可以使用 unicode 和十进制格式设置货币符号。如下面的代码所示:

例如,设置印度货币符号和格式化值。这将在用户不更改设置的情况下工作。

    Locale locale = new Locale("en","IN");
DecimalFormat decimalFormat = (DecimalFormat) DecimalFormat.getCurrencyInstance(locale);
DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(locale);
dfs.setCurrencySymbol("\u20B9");
decimalFormat.setDecimalFormatSymbols(dfs);
System.out.println(decimalFormat.format(payment));

产出:

₹12,324.13

在 Android Android.icu.text 上。NumberFormat 仅在 api 级别24之后可用。因此,为了支持较低的版本,我用 Java 编写了自己的方法。

public static String formatIndianCommaSeparated(long rupee){
// remove sign if present
String raw = String.valueOf(Math.abs(rupee));
int numDigits = raw.length();
StringBuilder sb = new StringBuilder(raw);
// Reverse the string to start from right most digits
sb = sb.reverse();
// Counter to keep track of number of commas placed
int commas = 0;
for (int i=0; i<numDigits; i++){
// Insert a comma if i is in the range [3, 5, 7, 9, ...)
if (i % 2 == 1 && i != 1 ){
sb.insert(i+commas, ",");
commas++;
}
}
// Reverse the string back to get original number
String sign = (rupee < 0) ? "-" : "";
return sign + sb.reverse().toString();
}

Kotlin 版本,可以在 Android API 26上运行

fun currencyLocale(value: Double): String {
val formatter = NumberFormat.getCurrencyInstance(Locale("en", "in"))
return formatter.format(value)
}


fun parseCommaSeparatedCurrency(value: String): Number {
return NumberFormat.getCurrencyInstance(Locale("en", "in")).parse(value)
}

下面是我探索的几个选项

    import java.text.NumberFormat;
import java.util.Locale;


class NumberFormatDemo {


public static void main(String[] args) {
Double d = 45124853123456.78941;
NumberFormat nf = NumberFormat.getInstance(Locale.ITALY);
System.out.println("ITALY representation of " + d + " : " + nf.format(d));


nf = NumberFormat.getInstance(Locale.GERMANY);
System.out.println("GERMANY representation of " + d + " : " + nf.format(d));


nf = NumberFormat.getInstance(Locale.CHINESE);
System.out.println("CHINESE representation of " + d + " : " + nf.format(d));


nf = NumberFormat.getInstance(Locale.US);
System.out.println("US representation of " + d + " : " + nf.format(d));


nf = NumberFormat.getInstance(Locale.ENGLISH);
System.out.println("ENGLISH representation of " + d + " : " + nf.format(d));


nf = NumberFormat.getInstance(Locale.UK);
System.out.println("UK representation of " + d + " : " + nf.format(d));


//===================================================
//ICU4j example
com.ibm.icu.text.NumberFormat format = com.ibm.icu.text.NumberFormat.getCurrencyInstance(new Locale("en", "in"));
System.out.println("INDIA representation of " + d + " : " + nf.format(d));
}
}

最后一个重新获得下列依赖项

<dependency>
<groupId>com.ibm.icu</groupId>
<artifactId>icu4j</artifactId>
<version>65.1</version>
</dependency>
 fun currencyFormatter(inputNumbers: String?): String {
var formattedNumber = ""
var decimalPoint=""
var inputNumber=""


if (inputNumbers != null) {
try {
val sp=inputNumbers.split(".")
inputNumber=sp[0]
decimalPoint=sp[1]
} catch (e: Exception) {
inputNumber=inputNumbers
}




formattedNumber = when {
inputNumber.length <= 3 -> {
inputNumber
}
inputNumber.length <= 5 -> {
String.format("%s,%s", inputNumber.substring(0, inputNumber.length - 3),
inputNumber.substring(inputNumber.length - 3))
}
inputNumber.length <= 7 -> {
String.format("%s,%s,%s",
inputNumber.substring(0, inputNumber.length - 5),
inputNumber.substring(inputNumber.length - 5, inputNumber.length - 3),
inputNumber.substring(inputNumber.length - 3)
)
}
inputNumber.length <= 9 -> {
String.format("%s,%s,%s,%s",
inputNumber.substring(0, inputNumber.length - 7),
inputNumber.substring(inputNumber.length - 7, inputNumber.length - 5),
inputNumber.substring(inputNumber.length - 5, inputNumber.length - 3),
inputNumber.substring(inputNumber.length - 3)
)
}
else -> inputNumber
}
}
return "$formattedNumber.$decimalPoint"
}


main(){
val rs=1200.55f
print(currencyFormatter(rs.toString()))
}


public static String paiseToString(long paise)
{
DecimalFormat fmt = new DecimalFormat("#0.00");
boolean minus = paise < 0;
StringBuilder sb = new StringBuilder(fmt.format(Math.abs(paise)/100.0));
for (int index = sb.length()-6; index > 0; index-=2)
{
sb.insert(index,',');
}
if (minus)
sb.insert(0,'-');
return sb.toString();
}


public static String rupeesToString(long rupees)
{
boolean minus = rupees < 0;
StringBuilder sb = new StringBuilder(Long.toString(Math.abs(rupees)));
for (int index = sb.length()-3; index > 0; index-=2)
{
sb.insert(index,',');
}
if (minus)
sb.insert(0,'-');
return sb.toString();
}


// Test the functions
public static void main(String[] args)
{
// Test for positive values
long val = 1;
while (val < Long.MAX_VALUE/10)
{
System.out.printf("%28s %28s\n",paiseToString(val),rupeesToString(val));
val *= 10;
}
// Test for negative values
val = -1;
while (val > Long.MIN_VALUE/10)
{
System.out.printf("%28s %28s\n",paiseToString(val),rupeesToString(val));
val *= 10;
}
}

对我来说,在安卓系统中工作得很好:

public static String priceFormatWithDec(String price) {
DecimalFormat decimalFormat = new DecimalFormat("#,##,###.00");
String format = decimalFormat.format(Double.parseDouble(price));
return String.format("%s", format);
}

使用 Locale 类和 getCurrencyInstance 可以获得印度货币格式。

在为印度定义新的 Locale 时,使用“ en”表示英语,使用“ hi”表示印地语。

有关本地语言环境,请参阅 https://docs.oracle.com/javase/8/docs/api/java/util/Locale.html

为 getCurrencyInstance 引用 https://docs.oracle.com/javase/8/docs/api/java/text/NumberFormat.html#getCurrencyInstance--

这里有一个相同的小实现。

import java.util.*;
import java.text.*;
import java.text.NumberFormat;
import java.util.Locale;


public class Solution {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double payment = scanner.nextDouble();
scanner.close();


Locale indialocale=new Locale("en","IN");
NumberFormat india  = NumberFormat.getCurrencyInstance(indialocale);
System.out.println("India: " + india.format(payment));
}

}

这是为我工作. 。

public String indianCurrencyFormat(String s) {


String orignalNo = s;
String formatted = "";


if(orignalNo.startsWith("-")) {
s = s.replace("-","");
}


if(orignalNo.contains(".")) {
if(s.length() > 6){
StringBuilder sb=new StringBuilder(s);
s = sb.reverse().toString();


formatted = s.substring(0,6);
s = s.substring(6);


while(s.length() > 1) {
formatted += "," + s.substring(0,2);
s = s.substring(2);
}


sb = new StringBuilder(formatted+(StringUtils.isNotBlank(s) ? ","+s :""));
formatted = sb.reverse().toString();
} else {
formatted = s;
}
} else {
if(s.length() > 3){
StringBuilder sb=new StringBuilder(s);
s = sb.reverse().toString();


formatted = s.substring(0,3);
s = s.substring(3);


while(s.length() > 1) {
formatted += "," + s.substring(0,2);
s = s.substring(2);
}


sb = new StringBuilder(formatted+(StringUtils.isNotBlank(s) ? ","+s :""));
formatted = sb.reverse().toString();
} else {
formatted = s;
}
}


if (orignalNo.startsWith("-")){
formatted = "-"+formatted;
}


return formatted;
}

试试这个:

NumberFormat.getCurrencyInstance(new Locale("en","IN")).format(number)

“ en”代表英语。 “ IN”代表国家(印度)。

我知道这是一个古老的问题,但为了以防万一,我会补充我的答案。可以通过迂回的方式使用同一个十进制格式化程序来获得结果,但这不是最有效的解决方案,只是一个更简单的解决方案。

import java.math.RoundingMode;
import java.text.DecimalFormat;


public class IndianMoneyFormat {


static String indianCurrencyFormat(double money) {
String result = null;


double aboveThousands = money / 1000;
double thousands = money % 1000;


if (aboveThousands > 1) {
DecimalFormat formatter = new DecimalFormat("##,##");
formatter.setRoundingMode(RoundingMode.DOWN); //will round towards zero whether negative or positive. Same as truncating.
String one = formatter.format(aboveThousands);


formatter.applyPattern("###.00");
formatter.setRoundingMode(RoundingMode.HALF_EVEN); //default rounding mode of DecimalFormat
String two = formatter.format(thousands);


result = one + "," + two;
return result;
} else {
DecimalFormat formatter = new DecimalFormat("###.00");
result = formatter.format(money);
return result;
}
}


public static void main(String[] args) {
double money1 = 123000999.5;
double money2 = 999.39;
System.out.println(indianCurrencyFormat(money1));
System.out.println(indianCurrencyFormat(money2));
}
}

以上代码将提供以下结果:

12,30,00,999.50
999.39

请找到下面的代码片段,通过输入根据地区打印货币

import java.util.*;
import java.text.*;


public class CurrencyPayment {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double payment = scanner.nextDouble();
scanner.close();


System.out.println("US: " + NumberFormat.getCurrencyInstance(Locale.US).format(payment));
System.out.println("India: " + NumberFormat.getCurrencyInstance(new Locale("en","IN")).format(payment));
System.out.println("China: " + NumberFormat.getCurrencyInstance(Locale.CHINA).format(payment));
System.out.println("France: " + NumberFormat.getCurrencyInstance(Locale.FRANCE).format(payment));
}
}

  1. 在 Golang 将任意数字转换成印度卢比格式。
  2. 函数 IndianRupeeFormat 接受字符串形式的参数,并以字符串形式返回
    func IndianRupeeFormat(DisplayAmount string) string {
    AmountDisplayed := DisplayAmount[:len(DisplayAmount)-3] // just removing decimal point numbers.
    IndianRupee := ""
    if len(AmountDisplayed) > 3 { // amount should to greater than 999 if "," should appear , so length should be greater than 3
    startIndex := math.Mod(float64(len(AmountDisplayed)), 2) // startIndex is taken as slicing part to add comma.
    noOfCommas := (len(AmountDisplayed) / 2) - 1             // No of Commas appear in the number.
    startSlice := 0                                          // start of the slice
    for i := 0; i < noOfCommas; i++ {
    IndianRupee = IndianRupee + DisplayAmount[startSlice:int64(startIndex)+1] + ","
    startIndex = startIndex + 2 // adding +2 because after first comma we are skipping 2 digits to add another comma.
    startSlice = int(startIndex) - 1
    }
    k := len(DisplayAmount) - 6
    IndianRupee = IndianRupee + DisplayAmount[k:] // adding the rest of digits.
    } else {
    IndianRupee = DisplayAmount
    }
    return IndianRupee
    }
    
    
    Amount1 := IndianRupeeFormat(fmt.Sprintf("%.2f",100))
    Amount2 := IndianRupeeFormat(fmt.Sprintf("%.2f",1000.345))
    Amount3 := IndianRupeeFormat(fmt.Sprintf("%.2f",10000.02))
    Amount4 := IndianRupeeFormat(fmt.Sprintf("%.2f",100000.100))
    Amount5 := IndianRupeeFormat(fmt.Sprintf("%.2f",1000000.))
    Amount6 := IndianRupeeFormat(fmt.Sprintf("%.2f",1000.090))
    fmt.Println(Amount1)
    fmt.Println(Amount2)
    fmt.Println(Amount3)
    fmt.Println(Amount4)
    fmt.Println(Amount5)
    fmt.Println(Amount6)
    // Output: 100
    // Output: 1,000.34
    // Output: 10,000.02
    // Output: 1,00,000.10
    // Output: 10,00,000.00
    // Output: 1,000.90
    

这对我很有效:

fun getFormattedPrice(price: Double?): String {
if (price == null) return "0"
val formatter = DecimalFormat("##,##,###.00").format(price)
var formattedPrice = formatter.format(price)
if (formattedPrice.endsWith(".00")) formattedPrice = formattedPrice.dropLast(3)
if (formattedPrice.isEmpty()) formattedPrice = "0"
return formattedPrice
}