public class Test {
public static void main(String[] args) {
final String test1 = new String("01,");
final String test2 = new String("01,0");
final String test3 = new String("1,00");
String pattern = "##,##";
DecimalFormat formatter;
DecimalFormatSymbols dfs = new DecimalFormatSymbols();
dfs.setGroupingSeparator(',');
formatter = new DecimalFormat(pattern, dfs);
String result1 = formatter.format(test1);
String result2 = formatter.format(test2);
String result3 = formatter.format(test3);
System.out.println("Result 1 == " + result1);
System.out.println("Result 2 == " + result2);
System.out.println("Result 3 == " + result3);
}
}
I am trying to format the string. I added the code which I am using for formatting. I am getting exception.
I want result as 01,00 for all of this.
EXCEPTION -
Exception in thread "main" java.lang.IllegalArgumentException: Cannot format given Object as a Number
at java.text.DecimalFormat.format(DecimalFormat.java:487)
at java.text.Format.format(Format.java:140)
at com.test.Test.main(Test.java:21)
If anyone has any idea please guide me.
DecimalFormat.format accepts only Date or Number objects, not String!
EDIT-1:
1) String pattern = "00.00"
2)
String result1 = formatter.format(formatter.parse(test1));
String result2 = formatter.format(formatter.parse(test2));
String result3 = formatter.format(formatter.parse(test3));
For example:
for
final String test1 = new String("01,");
final String test2 = new String("02,3");
final String test3 = new String("1,00");
it gives me:
Result 1 == 01,00
Result 2 == 02,30
Result 3 == 01,00
This is how it should be used.
format = new DecimalFormat(".00");
format.format(10.0);
String s = (String.format("%,d", 1000000)).replace(',', ' ');
int minutes = (int) secondsLeft / 60;
int seconds = secondsLeft - minutes * 60;
String upDatePattern ;
upDatePattern = (String.format("%02d:%02d", minutes,seconds));
timerTextView.setText(upDatePattern);
this produces a zero padded "timer" with min/sec
ex: 02:35
you can find lots of formatting examples on "Formatter | Android Developers
Related
So I have a string like this: <em>1234</em>56.70
it's basically a number where the em tags help identify what to highlight in the string
I need to first convert the string to an actual number with the current locale format. So I remove the em tags (replaceAll by emptyString) and then use the numberFormat java API to get a string like: $123,456.70
The problem with this is, I lost the highlight (em) tags. So I need to put it back in the string that is formatted, something like this: <em>$123,4</em>56.70
highlightValue = "<em>1234</em>56.70";
highlightValue = highlightValue.replaceAll("<em>", "").replaceAll("</em>", ""); // highlightValue is now 123456.70
highlightValue = numberFormat.convertToFormat(highlightValue, currencyCode); // highlightValue is now $123,456.70
highlightValue = someFunction(highlightValue); // this function needs to return <em>$123,4</em>56.70
I am not sure what approach to use. I was trying pattern matching but didn't know how to achieve it.
All help appreciated !
I am assuming that you want to highlight the number from starting up to some number of digits.This can be done.
In the initial string count the number of digits after which the tag is present. The starting tag will always be placed at the beginning. It is the ending tag you have to worry about. Now count the number of digits, excluding any other symbols.When the required number of digits have been passed, again place the tag. Either you can create a StringBuilder from the String highlighted and insert the tag string directly, or divide the string into two substrings and then join them together with the tag string in the middle.
Hope this helped.
I took an approach, where I count the numbers in front of the tag, in the middle of the tag - as I think no formatting will actually change the numbers(assuming you don't add leading zeroes) and after that I insert back the tag based on the numbers which were in front of the tag or for the closing tag in front and inside
so this is the code:
public static void main(String[] args) {
String input1 = "<em>1234</em>56.70";
String result1 = formatString(input1, "em");
System.out.printf("input1 = %s%n", input1);
System.out.printf("result1 = %s%n", result1);
String input2 = "<em>8127</em>29.12";
String result2 = formatString(input2, "em");
System.out.printf("input2 = %s%n", input2);
System.out.printf("result2 = %s%n", result2);
}
private static String formatString(String input, String tagName) {
String tagOpening = String.format("<%s>", tagName);
int tagOpeningLength = tagOpening.length();
String tagClosing = String.format("</%s>", tagName);
int tagClosingLength = tagClosing.length();
int inputLength = input.length();
int tagOpeningPos = input.indexOf(tagOpening);
int tagClosingPos = input.indexOf(tagClosing, tagOpeningPos);
String beforeTag;
if(tagOpeningPos > 0)
beforeTag = input.substring(0, tagOpeningPos);
else
beforeTag = "";
int digitsInBeforeTag = countNumbers(beforeTag);
String tagValue;
if(tagOpeningPos + tagOpeningLength < tagClosingPos)
tagValue = input.substring(tagOpeningPos + tagOpeningLength, tagClosingPos);
else
tagValue = "";
int digitsInTagValue = countNumbers(tagValue);
String afterTag;
if((tagClosingPos + tagClosingLength) < inputLength)
afterTag = input.substring(tagClosingPos + tagClosingLength);
else
afterTag = "";
String valueToBeFormatted = beforeTag + tagValue + afterTag;
double value = Double.parseDouble(valueToBeFormatted);
NumberFormat nf = NumberFormat.getInstance(Locale.ENGLISH);
String formattedValue = nf.format(value);
int newEmOpeningPos = findSubstringWithThisManyNumbers(formattedValue, digitsInBeforeTag);
int newEmClosingPos = findSubstringWithThisManyNumbers(formattedValue, digitsInBeforeTag+digitsInTagValue);
StringBuilder result = new StringBuilder();
result.append(formattedValue.substring(0, newEmOpeningPos));
result.append(tagOpening);
result.append(formattedValue.substring(newEmOpeningPos, newEmClosingPos));
result.append(tagClosing);
result.append(formattedValue.substring(newEmClosingPos));
return result.toString();
}
private static int findSubstringWithThisManyNumbers(String input, int digitCount) {
int pos = 0;
int counter = 0;
for(char c : input.toCharArray()) {
if(counter >= digitCount)
break;
if(Character.isDigit(c))
counter++;
pos++;
}
return pos;
}
private static int countNumbers(String str) {
int result = 0;
for(char c : str.toCharArray())
if(Character.isDigit(c))
result++;
return result;
}
the output was
input1 = <em>1234</em>56.70
result1 = <em>123,4</em>56.7
input2 = <em>8127</em>29.12
result2 = <em>812,7</em>29.12
I don't know how can this be practical. But anyway.
String highlightValue = "0<em>1234</em>56.70";
int startIndex = highlightValue.indexOf("<em>");
String startString = highlightValue.substring(0, startIndex);
String endString = highlightValue.substring(highlightValue.indexOf("</em>") + "</em>".length());
highlightValue = highlightValue.replaceAll("<em>", "").replaceAll("</em>", "");
highlightValue = numberFormat.convertToFormat(highlightValue, currencyCode);
// highlightValue is now $123,456.70
int endIndex = highlightValue.indexOf(endString);
highlightValue = startString + "<em>" + highlightValue.substring(0, endIndex) + "</em>" + endString;
System.out.println(highlightValue);
// 0<em>$123,4</em>56.70
I want seven digit after dividing a integer,i have ddhh.mmmmm lat long I have to convert it dd.(hhmmmm/60) with 7 digit after point.
My code:
public static String getCoordinates(String data) {
System.out.println(data);
String mm = data.substring(2).replace(".", "");
int int_mm = Integer.parseInt(mm);
double d_mm = int_mm / 60.00000000;
String s_mm = Double.toString(d_mm);
s_mm = s_mm.replace(".", "");
String s_dd = data.substring(0, 2);
return s_dd + "." + s_mm;
}
Input
2838.9544
Output
28.64924
Input
7716.7731
Output
77.2795516666666667
two same input but is not same how can i solve it?
You can do it like that:
Double result=Double.parseDouble(s_dd + "." + s_mm);
NumberFormat formatter = new DecimalFormat("#0.000000");
return formatter.format(result);
java.math.BigDecimal
in java has the following future for your problem.
double d = Double.valueOf(152452+"."+45545545);
BigDecimal bd = BigDecimal.valueOf(d);
bd = bd.setScale(7, RoundingMode.CEILING);
In this example bd is equals to 152452.4554555
Is it possible to have an obligatory sign in mantissa?
For example I would like to get 0.01 and 1040.3 formatted using the same DecimalFormat as:
1.00000e-002 and 1.040300e+003
At the moment I'm using:
DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.getDefault() );
otherSymbols.setDecimalSeparator('.');
otherSymbols.setExponentSeparator("e");
format="0.00000E000";
DecimalFormat formatter = new DecimalFormat(format, otherSymbols);
but this pattern fails to display '+' in mantissa.
I don't think this is possible using DecimalFormat. However, you could use something like this:
public static void main(String[] args) {
System.out.println(format(1040.3, "0.000000E000"));
}
public static String format(double number, String pattern) {
DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.getDefault());
otherSymbols.setDecimalSeparator('.');
otherSymbols.setExponentSeparator("e");
DecimalFormat formatter = new DecimalFormat(pattern, otherSymbols);
String res = formatter.format(number);
int index = res.indexOf('e') + 1;
if (res.charAt(index) != '-') {
res = res.substring(0, index) + "+" + res.substring(index);
}
return res;
}
This results in the String you desired, 1.040300e+003.
Running this method gives a string of total post output
String numberOfPost = test.runNewAdvancedSearch(query, waitTime, startDate, endDate, selectedBrowser, data1, "");
int numberOfPostsInt = Integer.parseInt(numberOfPosts.replace(",", ""));
this parseInt does not work
How do I parse this out below?
"Total Posts: 5,203"
Try this fully functional example:
public class Temp {
public static void main(String[] args) {
String s = "Total Posts: 5,203";
s = s.replaceAll("[^0-9]+", "");
System.out.println(s);
}
}
Meaning of the regex pattern [^0-9]+ - Remove all characters which occurs one or more times + which does NOT ^ belong to the list [ ] of characters 0 to 9.
if comma is decimal separator:
double d = Double.parseDouble(s.substring(s.lastIndexOf(' ') + 1).replace(",", "."));
if comma is grouping separator:
long d = Long.parseLong(s.substring(s.lastIndexOf(' ') + 1).replace(",", ""));
Try This:
String numberOfPost = test.runNewAdvancedSearch(query, waitTime, startDate, endDate, selectedBrowser, data1, ""); // get the parse string "Total Posts: 5,203
int index = numberOfPost.lastIndexOf(":");
String number = numberOfPost.substring(index + 1);
int numOfPost = Integer.parseInt(number.replace(",", "").trim());
System.out.println(numOfPost); // 5203enter code here
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.