Pattern for Integers in Java (###.###.###) - java

I need to format Integers to a different pattern.
Example:
Input: 13040321
Output: 13.040.321
Example2:
Input: 2323
Output: 2.323
I tried use it:
String pattern = "###.###.###";
DecimalFormat decimalFormat = new DecimalFormat(pattern); //ERROR HERE
decimalFormat.setGroupingSize(3);
String formattedValue = decimalFormat.format(value);
return formattedValue;
I cannot have outputs using "," or decimals.

By looking at the DecimalFormat docs, I can say, that . is used for decimal separator. If you would like to group numbers, you should use , instead. Also you should specify locale, so the following code should work fine:
DecimalFormat decimalFormat = new DecimalFormat();
decimalFormat.setGroupingSize(3);
DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols();
decimalFormatSymbols.setGroupingSeparator('.');
decimalFormat.setDecimalFormatSymbols(decimalFormatSymbols);
System.out.println(decimalFormat.format(value));

The DecimalFormat's pattern requires you use the comma as the grouping character. So your pattern has to be #,###. Since you want to output periods for grouping, you would need to set your own DecimalFormatSymbols setDecimalFormatSymbols
I assume this formatting is consistent for a particular locale. But if it isn't, your can construct your own custom instance...

An extremely dirty (but working) solution:
public static String pattern(int number) {
String textValue = String.valueOf(number);
StringBuilder sb = new StringBuilder(textValue);
String reversedTextValue = sb.reverse().toString();
StringBuilder result = new StringBuilder();
for(int i = 0; i < reversedTextValue.length(); i++) {
result.append(i % 3 == 0 ? "." + reversedTextValue.charAt(i) : reversedTextValue.charAt(i));
}
return result.reverse().toString().substring(0, result.length() - 1);
}

String getPattern(Integer i, String pattern) {
//assumes a pattern that uses '#' to represent where a digit goes
int y = 0;
StringBuilder sb = new StringBuilder();
String iStr = Integer.toString(i);
for (int x = 0; x < iStr.length(); i++) {
while (y < pattern.length()) {
if ('#' == pattern.charAt(y)) {
sb.append(iStr.charAt(x));
y++;
break;
} else {
sb.append(pattern.charAt(y));
y++;
}
}
}
return sb.toString();
}

Related

How to find the words starting after line breaks, using regex, Java?

I have an input string, consisting of several lines, e.g.:
When I was younger
I never needed
And I was always OK
but it was a long Time Ago
The problem is to invert first letters of all the words which length is more than 3. That is an output must be the following:
when I Was Younger
I Never Needed
and I Was Always OK
But it Was a Long time ago
There is my code:
import java.util.regex.*;
public class Part3_1 {
public static void main(String[] args) {
String str = "When I was younger\r\nI never needed\r\nAnd I was always OK\r\nbut it was a long Time Ago";
System.out.println(convert(str));
}
public static String convert(String str) {
String result = "";
String[] strings = str.split(" ");
String regexLowerCase = "\\b[a-z]{3,}\\b";
String regexLowerCaseInitial = "(\\r\\n)[a-z]{3,}\\b";
String regexUpperCase = "\\b([A-Z][a-z]{2,})+\\b";
String regexUpperCaseInitial = "(\\r\\n)([A-Z][a-z]{2,})\\b";
Pattern patternLowerCase = Pattern.compile(regexLowerCase, Pattern.MULTILINE);
Pattern patternUpperCase = Pattern.compile(regexUpperCase, Pattern.MULTILINE);
Pattern patternLowerCaseInitial = Pattern.compile(regexLowerCaseInitial, Pattern.MULTILINE);
Pattern patternUpperCaseInitial = Pattern.compile(regexUpperCaseInitial, Pattern.MULTILINE);
for (int i = 0; i < strings.length; i++) {
Matcher matcherLowerCase = patternLowerCase.matcher(strings[i]);
Matcher matcherUpperCase = patternUpperCase.matcher(strings[i]);
Matcher matcherLowerCaseInitial = patternLowerCaseInitial.matcher(strings[i]);
Matcher matcherUpperCaseInitial = patternUpperCaseInitial.matcher(strings[i]);
char[] words = strings[i].toCharArray();
if (matcherLowerCase.find() || matcherLowerCaseInitial.find()) {
char temp = Character.toUpperCase(words[0]);
words[0] = temp;
result += new String(words);
} else if (matcherUpperCase.find() || matcherUpperCaseInitial.find()) {
char temp = Character.toLowerCase(words[0]);
words[0] = temp;
result += new String(words);
} else {
result += new String(words);
}
if (i < strings.length - 1) {
result += " ";
}
}
return result;
}
}
Here:
"\\b[a-z]{3,}\\b" is a regular expression, selecting all words in lower case which length is 3 or more symbols,
"\\b([A-Z][a-z]{2,})+\\b" is a regular expression, selecting all words starting from capital letter which length is 3 or more symbols.
Both regular expressions works properly but when we have a line breaks - they do not work. The output of my program execution is following:
when I Was Younger
I Never Needed
And I Was Always OK
but it Was a Long Time ago
As I understood, these regular expressions cannot select words And and but from needed\r\nAnd and OK\r\nbut respectively.
To fix this bug I tried to add new regular expressions "(\\r\\n)[a-z]{3,}\\b" and "(\\r\\n)([A-Z][a-z]{2,})\\b", but they do not work.
How to compose the regular expressions, selecting words after line breaks?
One option would be to split the string on a word break (\b) instead, and then pass the white space through to the final string in the strings array. This removes the need to have separate regex for the different situations, and also the need to add back space characters. This will give you the results you want:
public static String convert(String str) {
String result = "";
String[] strings = str.split("\\b");
String regexLowerCase = "^[a-z]{3,}";
String regexUpperCase = "^[A-Z][a-z]{2,}+";
Pattern patternLowerCase = Pattern.compile(regexLowerCase, Pattern.MULTILINE);
Pattern patternUpperCase = Pattern.compile(regexUpperCase, Pattern.MULTILINE);
for (int i = 0; i < strings.length; i++) {
Matcher matcherLowerCase = patternLowerCase.matcher(strings[i]);
Matcher matcherUpperCase = patternUpperCase.matcher(strings[i]);
char[] words = strings[i].toCharArray();
if (matcherLowerCase.find()) {
char temp = Character.toUpperCase(words[0]);
words[0] = temp;
result += new String(words);
} else if (matcherUpperCase.find()) {
char temp = Character.toLowerCase(words[0]);
words[0] = temp;
result += new String(words);
} else {
result += new String(words);
}
}
return result;
}
Output:
when I Was Younger
I Never Needed
and I Was Always OK
But it Was a Long time ago
Demo on rextester

Grouping the numbers with comma in android

Eg:- double ab=1234567.00;
The expected output should be,
ab=12,34,567;
But the following format gives the default three digit grouping.
DecimalFormat df_separator = new DecimalFormat("###,###,##0.00");
Also tried with,
DecimalFormat df_separator = new DecimalFormat("###,##,##0.00");
still in vain.......
Here you are sir,
NumberFormat numberFormat = NumberFormat.getInstance();
String formattedNr = numberFormat.format(12345678L);
This will give you: 12,345,678.00
Edit:
public String formatDouble(double number)
{
String result = "";
String numberStr = String.valueOf(number);
char[] charArray = numberStr.toCharArray();
Character[] charObjectArray = ArrayUtils.toObject(charArray);
for (int i=charObjectArray.length()-1; i>=0 i++)
{
if (charObjectArray[i] == ".")
{
result = "." + result;
continue;
}
result = charObjectArray[i] + result;
if (i % 2 == 0) result = "," + result;
}
return result;
}
This is pseudo code as I don't have a JVM atm but it should (almost) do the job.
Edit: Finally
Add the following jar to your project: http://icu-project.org/apiref/icu4j/com/ibm/icu/text/NumberFormat.html
Format format = com.ibm.icu.text.NumberFormat.getCurrencyInstance(new Locale("en", "in"));
System.out.println(format.format(new BigDecimal("100000000")));
double ab=1234567.00;
String str = new DecimalFormat("#,##,##,###.00").format(ab);
Log.d("TAG", str);
try this.

Replacement of English numbers of a string with Arabic numbers

I'm going to find number chars in a String and replace them with their Arabic versions.
The Code is:
public static void main(String[] args) {
String pattern = "[0-9]+";
Pattern p = Pattern.compile(pattern);
String mainText = "34titi685dytti5685fjjfj8585443";
Matcher m = p.matcher(mainText);
int i = 0;
while (m.find()) {
System.out.println("Match number " + i);
String tmp = m.group();
char[] cTmp = tmp.toCharArray();
for (int j = 0; j < cTmp.length; j++) {
cTmp[j] = (char) ((int) cTmp[j] + 1584);
}
m.group().replaceFirst(tmp,new String(cTmp));
i++;
}
System.out.println(mainText);
}
But at the end it prints the same string mainText.
What is wrong with my code?
This is not how you do a replacement using Matcher. m.group() just gives you the matched part of the string. Whatever replacement you do in it, you have to perform concatenation with original string. This is due to the fact that Strings are immutable objects. You don't perform in-place replacement to it.
The proper way to do this is to create a StringBuffer object, and use Matcher#appendReplacement and Matcher#appendTail methods.
You do it like this:
StringBuffer buffer = new StringBuffer();
while (m.find()) {
String tmp = m.group();
char[] cTmp = tmp.toCharArray();
for (int j = 0; j < cTmp.length; j++) {
cTmp[j] = (char) (cTmp[j] + 1584); // You don't need to typecast `cTmp[j]` to `int`.
}
m.appendReplacement(buffer, new String(cTmp));
}
m.appendTail(buffer);
System.out.println(buffer.toString());
String is final and immutable, you have to assign the new string to itself.
use StringBuilder to append the values every time.
StringBuilder stringBuilder = new StringBuilder();
//
//
m.group().replaceFirst(stringBuilder,new String(cTmp));
instead of
m.group().replaceFirst(tmp,new String(cTmp));
Assign the outcoming value to the mainText

how to extract numeric values from input string in java

How can I extract only the numeric values from the input string?
For example, the input string may be like this:
String str="abc d 1234567890pqr 54897";
I want the numeric values only i.e, "1234567890" and "54897". All the alphabetic and special characters will be discarded.
You could use the .nextInt() method from the Scanner class:
Scans the next token of the input as an int.
Alternatively, you could also do something like so:
String str=" abc d 1234567890pqr 54897";
Pattern p = Pattern.compile("(\\d+)");
Matcher m = p.matcher(str);
while(m.find())
{
System.out.println(m.group(1));
}
String str=" abc d 1234567890pqr 54897";
Pattern pattern = Pattern.compile("\\w+([0-9]+)\\w+([0-9]+)");
Matcher matcher = pattern.matcher(str);
for(int i = 0 ; i < matcher.groupCount(); i++) {
matcher.find();
System.out.println(matcher.group());
}
Split your string into char array using yourString.toCharArray(); Then iterate through the characters and use Character.isDigit(ch); to identify if this is the numeric value. Or iterate through whole string and use str.charAt(i). For e.g:
public static void main(String[] args) {
String str = "abc d 1234567890pqr 54897";
StringBuilder myNumbers = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
if (Character.isDigit(str.charAt(i))) {
myNumbers.append(str.charAt(i));
System.out.println(str.charAt(i) + " is a digit.");
} else {
System.out.println(str.charAt(i) + " not a digit.");
}
}
System.out.println("Your numbers: " + myNumbers.toString());
}
You could do something like:
Matcher m = Pattern.compile("\\d+").matcher(str);
while (m.find()) {
System.out.println(m.group(0));
}
You can use str = str.replaceAll("replaced_string","replacing_string");
String str=" abc d 1234567890pqr 54897";
String str_rep1=" abc d ";
String str_rep2="pqr ";
String result1=str.replaceAll("", str_rep1);
String result2=str.replaceAll(",",str_rep2);
also what npinti suggests is fine to work with.
Example using java Scanner class
import java.util.Scanner;
Scanner s = new Scanner( "abc d 1234567890pqr 54897" );
s.useDelimiter( "\\D+" );
while ( s.hasNextInt() ){
s.nextInt(); // get int
}
If you do not want to use regex,
String str = " abc d 1234567890pqr 54897";
char[] chars = new char[str.length()];
int i = 0;
for (int j = 0; j < str.length(); j++) {
char c = str.charAt(j);
if (Character.isDigit(c)) {
chars[i++] = c;
if (j != chars.length - 1)
continue;
}
if (chars[0] == '\0')
continue;
String num = new String(chars).trim();
System.out.println(num);
chars = new char[str.length()];
i = 0;
}
Output :
1234567890
54897
String line = "This order was32354 placed 343434for 43411 QT ! OK?";
String regex = "[^\\d]+";
String[] str = line.split(regex);
String required = "";
for(String st: str){
System.out.println(st);
}
By above code you will get all the numeric values. then you can merge them or what ever you wanted to do with those numeric values.
You want to discard everything except digits and spaces:
String nums = input.replaceAll("[^0-9 ]", "").replaceAll(" +", " ").trim();
The extra calls clean up doubled and leading/trailing spaces.
If you need an array, add a split:
String[] nums = input.replaceAll("[^0-9 ]", "").trim().split(" +");
You could split the string on spaces to get the individual entries, loop across them, and try to parse them with the relevant method on Integer, using a try/catch approach to handle the cases where parsing it is as a number fails. That is probably the most straight-forward approach.
Alternatively, you can construct a regex to match only the numbers and use that to find them all. This is probably far more performant for a big string. The regex will look something like `\b\d+\b'.
UPDATE: Or, if this isn't homework or similar (I sort of assumed you were looking for clues to implementing it yourself, but that might not have been valid), you could use the solution that #npinti gives. That's probably the approach you should take in production code.
public static List<String> extractNumbers(String string) {
List<String> numbers = new LinkedList<String>();
char[] array = string.toCharArray();
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < array.length; i++) {
if (Character.isDigit(array[i])) {
stack.push(array[i]);
} else if (!stack.isEmpty()) {
String number = getStackContent(stack);
stack.clear();
numbers.add(number);
}
}
if(!stack.isEmpty()){
String number = getStackContent(stack);
numbers.add(number);
}
return numbers;
}
private static String getStackContent(Stack<Character> stack) {
StringBuilder sb = new StringBuilder();
Enumeration<Character> elements = stack.elements();
while (elements.hasMoreElements()) {
sb.append(elements.nextElement());
}
return sb.toString();
}
public static void main(String[] args) {
String str = " abc d 1234567890pqr 54897";
List<String> extractNumbers = extractNumbers(str);
for (String number : extractNumbers) {
System.out.println(number);
}
}
Just extract the digits
String str=" abc d 1234567890pqr 54897";
for(int i=0; i<str.length(); i++)
if( str.charAt(i) > 47 && str.charAt(i) < 58)
System.out.print(str.charAt(i));
Another version
String str=" abc d 1234567890pqr 54897";
boolean flag = false;
for(int i=0; i<str.length(); i++)
if( str.charAt(i) > 47 && str.charAt(i) < 58) {
System.out.print(str.charAt(i));
flag = true;
} else {
System.out.print( flag ? '\n' : "");
flag = false;
}
public class ExtractNum
{
public static void main(String args[])
{
String input = "abc d 1234567890pqr 54897";
String digits = input.replaceAll("[^0-9.]","");
System.out.println("\nGiven Number is :"+digits);
}
}
public static String convertBudgetStringToPriceInteger(String budget) {
if (!AndroidUtils.isEmpty(budget) && !"0".equalsIgnoreCase(budget)) {
double numbers = getNumericFromString(budget);
if( budget.contains("Crore") ){
numbers= numbers* 10000000;
}else if(budget.contains("Lac")){
numbers= numbers* 100000;
}
return removeTrailingZeroesFromDouble(numbers);
}else{
return "0";
}
}
Get numeric value from alphanumeric string
public static double getNumericFromString(String string){
try {
if(!AndroidUtils.isEmpty(string)){
String commaRemovedString = string.replaceAll(",","");
return Double.parseDouble(commaRemovedString.replaceAll("[A-z]+$", ""));
/*return Double.parseDouble(string.replaceAll("[^[0-9]+[.[0-9]]*]", "").trim());*/
}
}catch (NumberFormatException e){
e.printStackTrace();
}
return 0;
}
For eg . If i pass 1.5 lac or 15,0000 or 15 Crores then we can get numeric value from these fucntion . We can customize string according to our needs.
For eg. Result would be 150000 in case of 1.5 Lac
String str = "abc d 1234567890pqr 54897";
str = str.replaceAll("[^\\d ]", "");
The result will be "1234567890 54897".
String str = "abc34bfg 56tyu";
str = str.replaceAll("[^0-9]","");
output: 3456

Displaying Currency in Indian Numbering Format

I have a question about formatting the Rupee currency (Indian Rupee - INR).
Typically a value like 450500 is formatted and shown as 450,500. In India, the same value is displayed as 4,50,500
For example, numbers here are represented as:
1
10
100
1,000
10,000
1,00,000
10,00,000
1,00,00,000
10,00,00,000
Refer Indian Numbering System
The separators are after two digits, except for the last set, which is in thousands.
I've searched on the internet and people have asked to use the locale en_GB or pattern #,##,##,##,##0.00
I tried this on JSTL by using the following tag:
<fmt:formatNumber value="${product.price}" type="currency"
pattern="#,##,##,##,###.00"/>
But this does not seem to solve the issue.
Unfortunately on standard Java SE DecimalFormat doesn't support variable-width groups. So it won't ever format the values exactly as you want to:
If you supply a pattern with multiple grouping characters, the interval between the last one and the end of the integer is the one that is used. So "#,##,###,####" == "######,####" == "##,####,####".
Most number formatting mechanisms in Java are based on that class and therefore inherit this flaw.
ICU4J (the Java version of the International Components for Unicode) provides a NumberFormat class that does support this formatting:
Format format = com.ibm.icu.text.NumberFormat.getCurrencyInstance(new Locale("en", "in"));
System.out.println(format.format(new BigDecimal("100000000")));
This code will produce this output:
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).
With Android, this worked for me:
new DecimalFormat("##,##,##0").format(amount);
450500 gets formatted as 4,50,500
http://developer.android.com/reference/java/text/DecimalFormat.html - DecimalFormat supports two grouping sizes - the primary grouping size, and one used for all others.
here is simple thing u can do ,
float amount = 100000;
NumberFormat formatter = NumberFormat.getCurrencyInstance(new Locale("en", "IN"));
String moneyString = formatter.format(amount);
System.out.println(moneyString);
The output will be Rs.100,000.00.
I also got myself in same problem.
I was working with DecimalFormat.
I have no knowledge of JSTL but you can figure out something by my solution.
As, grouping size remains constant in DecimalFormat. I separated both parts, formatted them with different patterns and concat both. Here is the code.
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);
}
It will provide format like Indian Numbering System.
If you want decimal points, just add ".##" in both conditions.
"###" to "###.##" and "000" to "000.##".
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();
}
This is what i did, for getting Indian currency format. if input is 1234567890 means output is 1,23,45,67,890.
Try this:
NumberFormat.getCurrencyInstance(new Locale("en","IN")).format(number)
"en" is for English.
"IN" is for the country (India).
Just Copy past this function. :)
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);
}
The simple solution is -
Double amount = 5356673553123.0; //amount is an example ,can be used with any double value
**DecimalFormat IndianCurrencyFormat = new DecimalFormat("##,##,###.00");**
then use it as -
String formattedAmount = IndianCurrencyFormat.format(amount);
Please find below snippet to print currency according to locale by giving inputs
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));
}
}
If there is no default Locale available and the user doesn't make any change to the locale, we can go with setting the currency symbol using unicode and decimal formatting. As in the below code:
For e.g. Setting the Indian currency symbol and formatting the value. This will work without user making changes in the settings.
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));
Output:
₹12,324.13
On Android android.icu.text.NumberFormat is available after api level 24 only. So to support lower version I wrote my own method in 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 version, It works on 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)
}
Few options that I explored are as below
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));
}
}
The last one reacquires following dependency
<dependency>
<groupId>com.ibm.icu</groupId>
<artifactId>icu4j</artifactId>
<version>65.1</version>
</dependency>
//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 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;
}
}
The default methods in existing libraries can only show thousands seperator. so we need to write custom function for this. You can use multiple substring operation to get the desired result.
In java,
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;
}
And in 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;
}
You can see more details here.
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);
}
}
It is better answer and works dynamically instead of specifying single Locale in code manually.
public String convertToDefaultCurrencyFormat(String amountToConvert){
NumberFormat formatter = NumberFormat.getCurrencyInstance(Locale.getDefault());
String moneyString = formatter.format(Double.valueOf(amountToConvert));
return moneyString;
}
for Indian rupees format change Language in your Android device:
Setting > Language & Input Settings > choose English(India)
Output:
₹10,00,000 (Starting with Indian Rupee symbol)
Working fine for me in Android:
public static String priceFormatWithDec(String price) {
DecimalFormat decimalFormat = new DecimalFormat("#,##,###.00");
String format = decimalFormat.format(Double.parseDouble(price));
return String.format("%s", format);
}
using Locale class and getCurrencyInstance the Indian currency format can be obtained.
while defining the new Locale for India use "en" for English and "hi" for Hindi.
for locale refer https://docs.oracle.com/javase/8/docs/api/java/util/Locale.html
for getCurrencyInstance refer https://docs.oracle.com/javase/8/docs/api/java/text/NumberFormat.html#getCurrencyInstance--
here is a small implementation of the same.
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));
}
}
This is working for me ..
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;
}
It worked for me:
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
}
Try this:
double number = 100000.00
NumberFormat numberFormat = new NumberFormat();
Locale locale = new Locale("hi","IN");
numberFormat = Numberformat.getCurrencyInstance(locale);
double yourFormattedNumber = numberFormat(number);
OutPut = ₹1,00,000.00
//Remove "₹" using String.replace()
String myFormattedNumber = numberFormat.format(number).replace("₹","");
OutPut = 1,00,000.00
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()))
}
Converting any Number into Indian Rupee Format in Golang.
Function IndianRupeeFormat takes paramter as string and returns as string
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
I know this is an old question but I'll add my answer just in case. It is possible to use the same decimal formatter in a roundabout way to achieve the result but it isn't the most efficient solution, just a simpler one.
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));
}
}
Above code will provide the following result:
12,30,00,999.50
999.39
ALTER FUNCTION [dbo].[udf_CurrencyFormat](#UC varchar(50)) RETURNS
varchar(50) AS BEGIN declare #FC varchar(50),#Scale varchar(3),#i
bigint=1,#a int=3,#b int=2,#WhileLength bigint,#UCScale varchar(50),
#Con varchar(20) set #Scale=charindex('.',#UC) --if number has '.'
then value else '0' if(#Scale!='0') begin set #UCScale=#UC set
#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 begin set
#WhileLength=(cast(len(#UC) as bigint)-3)/2 while(#i<=#WhileLength) --
length-3/2=3 if length is 9 (cast(len(#UC) as bigint)-3)/2 begin set
#a=3*#i set #UC = stuff(#UC,#a,0,',') set #i=#i+1 end --while set
#FC=#UC end --if odd Scale '0' else if(cast(len(#UC) as bigint)%2=0)
--if even begin set #WhileLength=(((cast(len(#UC) as bigint)-1)-3)/2)+1 while(#i<=#WhileLength) begin if(#i=1) begin set
#UC=stuff(#UC,#b,0,',') end else begin set #b=#b+3 set
#UC=stuff(#UC,#b,0,',') end set #i=#i+1 end set #FC=#UC end
if(#Scale!='0') begin set #FC=#FC+#Con end --if(#Scale!='0') --set
#FC=#UC return #FC END

Categories

Resources