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
Related
How can I convert a String such as "12.34" to a double in Java?
You can use Double.parseDouble() to convert a String to a double:
String text = "12.34"; // example String
double value = Double.parseDouble(text);
For your case it looks like you want:
double total = Double.parseDouble(jlbTotal.getText());
double price = Double.parseDouble(jlbPrice.getText());
If you have problems in parsing string to decimal values, you need to replace "," in the number to "."
String number = "123,321";
double value = Double.parseDouble( number.replace(",",".") );
To convert a string back into a double, try the following
String s = "10.1";
Double d = Double.parseDouble(s);
The parseDouble method will achieve the desired effect, and so will the Double.valueOf() method.
double d = Double.parseDouble(aString);
This should convert the string aString into the double d.
Use new BigDecimal(string). This will guarantee proper calculation later.
As a rule of thumb - always use BigDecimal for sensitive calculations like money.
Example:
String doubleAsString = "23.23";
BigDecimal price = new BigDecimal(doubleAsString);
BigDecimal total = price.plus(anotherPrice);
You only need to parse String values using Double
String someValue= "52.23";
Double doubleVal = Double.parseDouble(someValue);
System.out.println(doubleVal);
Citing the quote from Robertiano above again - because this is by far the most versatile and localization adaptive version. It deserves a full post!
Another option:
DecimalFormat df = new DecimalFormat();
DecimalFormatSymbols sfs = new DecimalFormatSymbols();
sfs.setDecimalSeparator(',');
df.setDecimalFormatSymbols(sfs);
double d = df.parse(number).doubleValue();
String double_string = "100.215";
Double double = Double.parseDouble(double_string);
There is another way too.
Double temp = Double.valueOf(str);
number = temp.doubleValue();
Double is a class and "temp" is a variable.
"number" is the final number you are looking for.
This is what I would do
public static double convertToDouble(String temp){
String a = temp;
//replace all commas if present with no comma
String s = a.replaceAll(",","").trim();
// if there are any empty spaces also take it out.
String f = s.replaceAll(" ", "");
//now convert the string to double
double result = Double.parseDouble(f);
return result; // return the result
}
For example you input the String "4 55,63. 0 " the
output will the double number 45563.0
Using Double.parseDouble() without surrounding try/catch block can cause potential NumberFormatException had the input double string not conforming to a valid format.
Guava offers a utility method for this which returns null in case your String can't be parsed.
https://google.github.io/guava/releases/19.0/api/docs/com/google/common/primitives/Doubles.html#tryParse(java.lang.String)
Double valueDouble = Doubles.tryParse(aPotentiallyCorruptedDoubleString);
In runtime, a malformed String input yields null assigned to valueDouble
Used this to convert any String number to double when u need int just convert the data type from num and num2 to int ;
took all the cases for any string double with Eng:"Bader Qandeel"
public static double str2doubel(String str) {
double num = 0;
double num2 = 0;
int idForDot = str.indexOf('.');
boolean isNeg = false;
String st;
int start = 0;
int end = str.length();
if (idForDot != -1) {
st = str.substring(0, idForDot);
for (int i = str.length() - 1; i >= idForDot + 1; i--) {
num2 = (num2 + str.charAt(i) - '0') / 10;
}
} else {
st = str;
}
if (st.charAt(0) == '-') {
isNeg = true;
start++;
} else if (st.charAt(0) == '+') {
start++;
}
for (int i = start; i < st.length(); i++) {
if (st.charAt(i) == ',') {
continue;
}
num *= 10;
num += st.charAt(i) - '0';
}
num = num + num2;
if (isNeg) {
num = -1 * num;
}
return num;
}
String s = "12.34";
double num = Double.valueOf(s);
Try this,
BigDecimal bdVal = new BigDecimal(str);
If you want Double only then try
Double d = Double.valueOf(str);
System.out.println(String.format("%.3f", new BigDecimal(d)));
For example when I parse a string "12345678901234567890" to double using Double.parseDouble() it returns the value "12345678901234567000" since it can hold up to 17 digits.
I want to validate this scenario and the user should be allowed to pass only 17 digits. How do I do this?
Example :
1.2345678901234567890 is invalid because it has more than 17 digits total
1.2345E+10 is valid
Tried something like this which can count the digits using split function
String input="12345678901234567E100";
String inputWithoutSign;
int lengthFullNumber;
int lengthFraction;
double v = Double.parseDouble(input);
if(input.startsWith("+") || input.startsWith("-")){
inputWithoutSign = input.split("[-+]",2)[1];
}
else inputWithoutSign = input;
String num = inputWithoutSign.split("[eE]", 2)[0];
if(num.indexOf('.') == -1){
lengthFullNumber = num.length();
lengthFraction = 0;
}else{
String[] splitNum = num.split("\\.", 2);
lengthFullNumber = splitNum[0].length();
lengthFraction = splitNum[1].length();
}
System.out.println("length:"+(lengthFullNumber+lengthFraction));
Presuming I understand your goal of limiting the number of digits, this may help solve the problem.
Test cases
String[] vals = {
"12345678901234567890", "123456789091919191919",
"182828282.18282828", "182828282.182828282", "191929e10",
"192929.22929e10"
};
Try and parse them
for (String v : vals) {
// remove possible decimal point and signs
String test = v.replaceAll("[.+-]", "");
// remove any exponents at end of string
test = test.replace("\\D+.*", "");
if (test.length() > 17) {
System.out.println(v + " has too many digits");
continue;
}
double d = Double.parseDouble(v);
System.out.println(v + " parses to " + d);
}
I know how to split decimal values. But I'm little bit confused how to split 31.07 or 71.008 something like this. if I'm using this below code , the value splitted like this 31 and 0.7
I need a Solution to be: 31 and 0.07. How can I solve my problem?
Here java code:
String decimal_value = String.format("%.2f", update_fare);
String[] arr = decimal_value.split("\\.");
if (arr.length == 2) {
int[] intArr = new int[2];
String before_decimal = String.valueOf(intArr[0] = Integer.parseInt(arr[0]));
String after_decimal = String.valueOf(intArr[1] = Integer.parseInt(arr[1]));
fare_tv.setText(String.valueOf(before_decimal));
fare_tv_decimal.setText(String.valueOf(after_decimal));
System.out.println("----------------updated fare intArr[0]---------" + intArr[0]);
System.out.println("----------------updated fare intArr[1]---------" + intArr[1]);
}
if A is your number, for example - A = 31.03,
And you want to split it like 31 and 0.03 into B and C, you can do something like that:
A = 31.03; // your number
B = a%1; // XX.00
C = A-B; // 00.XX
Assuming that you are working only with positive doubles, the following code might help you:
int total = (int)update_fare; //gets the whole part
double rem = update_fare - total; //gets the value after the dot
You can then use a proper formatter to convert them to strings as follows:
String rem_str = String.format("%.2f", rem);
String total_str = String.format("%d", total);
However, be careful of using this technique when dealing with negative numbers. You need to change some parts based on the sign of the value.
Try this
String value = "31.07";
String[] values = value.split("\\.");
if(values.length==2)
{
int[] intArr = new int[2];
String value1 = values[0];
String value2 = "0."+values[1];
fare_tv.setText(String.valueOf(value1));
fare_tv_decimal.setText(String.valueOf(value2));
intArr[0] = Integer.parseInt(value1);
intArr[0] = Integer.parseInt(value2);
}
Try this:
String value = "31.07";
String[] values = value.split("\\.");
if(values.length==2)
{
double[] intArr = new double[2];
String value1 = values[0];
String value2 = "0."+values[1];
fare_tv.setText(String.valueOf(value1));
fare_tv_decimal.setText(String.valueOf(value2));
intArr[0] = Double.parseDouble(value1);
intArr[1] = Double.parseDouble(value2);
System.out.println("----------------updated fare intArr[0]---------" + intArr[0]);
System.out.println("----------------updated fare intArr[1]---------" + intArr[1]);
}
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.
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