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]);
}
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 am trying to write a simple code for polynomial multiplication. I think it is logical to take inputs as strings such as "3x^2".
Problem is I don't know what to do with the 'x's in it. How can I turn them into something that can be multiplied? What should the logic be? I am totally new in Java and I really need help.
For example:
String s = "x^2";
String s2 = "3x^5";
//(Multiply them)
result = 3x^7
public static int[] multiply(String term1, String term2)
{
int[] t1 = parse(term1);
int[] t2 = parse(term2);
int[] ret = new int[2];
ret[0] = t1[0] * t2[0];
ret[1] = t1[1] + t2[1];
return ret;
}
public static int[] parse(String term)
{
int pos = term.indexOf("x^");
String coeffStr = term.substring(0, pos);
int coeff = Integer.parseInt(coeffStr);
String powerStr = term.substring(pos + 2);
int power = Integer.parseInt(powerStr);
int[] ret = new int[2];
ret[0] = coeff;
ret[1] = power;
return ret;
}
This will work for multiplying polynomials in the format Ax^n, x^n or Ax. I would put the terms you want to multiply into a List, and then parse the coefficients and powers into a HashMap, then use those to get you get your final result
List<String> terms = new ArrayList<>(Arrays.asList("x^2", "3x^5", "5x"));
Map<Integer,Integer> map = new HashMap<>();
for ( String term : terms ) {
String coefficient = term.split("x")[0].matches("") ? "1" : term.split("x")[0];
String[] exponent = term.split("x");
String power = exponent.length > 1 ? exponent[1].split("\\^")[1] : "1";
map.put(Integer.parseInt(coefficient), Integer.parseInt(power));
}
Integer finalCoefficient = 1;
Integer finalPower = 0;
for ( Integer coefficient : map.keySet() ) {
finalCoefficient *= coefficient;
finalPower += map.get(coefficient);
}
System.out.println(finalCoefficient + "x" + finalPower);
i have an integer values as:
1299129912
i want to store it as
12
12
12
in the int v1,v2,v3;
i.e.,when ever 9909 occurs we need to separate the values individually. Is it possible in java. If so please anyone help me.
here is the code I'm trying
int l = 1299129912;
Pattern p = Pattern.compile("99");
Matcher m1 = p.matcher(l);
if (m1.matches()) {
System.out.println("\n");
}
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method matcher(CharSequence) in the type Pattern is not applicable for the arguments (int)
I suppose you already have the value as a String since 1234990912349909 is more that Integer.MAX_VALUE. Then you can split the string into String[] and do whatever you want with the separate values. E.g. call parseInt on each element.
String[] values = myIntString.split("9909");
for (String value: values) {
int v = Integer.parseInt(value);
}
Yes, it is very possible in java. Just convert the integer to a string and replace the 9909 with a space.
Example:
String s="1234990912349909";
s=s.replaceAll("9909","");
int a=Integer.parseInt(s);
System.out.println(a);
//output would be 12341234
If you know you are always going to have 3 integers named v1, v2, and v3 the following would work:
String[] numbers = l.toString().split("99");
int v1 = Integer.parseInt(numbers[0]);
int v2 = Integer.parseInt(numbers[0]);
int v3 = Integer.parseInt(numbers[0]);
However if you don't know in advance then it might be better to do it like this:
String[] numbers = l.toString().split("99");
int[] v = new int[numbers.length];
for (int i = 0; i < numbers.length; i++)
v[i] = Integer.parseInt(numbers[i]);
I found out this is the easiest way to show you how you can resolve your issue:
I included clear comments on every important step. Please check this:
int num = 1239012390;
// Convert int into a string
String str = String.valueOf(num);
// What separates the values
String toBremoved = "90";
String str1 = "";
// Declare a String array to store the final results
String[] finalStrings = new String[2];
// i will be used as an index
int i = 0;
do {
// Finds and separates the first value into another string
finalStrings[i] = str.substring(0, str.indexOf(toBremoved));
// removes the first number from the original string
str = str.replaceFirst(finalStrings[i], "");
// Remove the next separating value
str = str.replaceFirst(str.substring(str.indexOf(toBremoved), str.indexOf(toBremoved) + toBremoved.length()), "");
// increments the index
i++;
} while (str.indexOf(toBremoved) > 0); // keeps going for a new iteration if there is still a separating string on the original string
// Printing the array of strings - just for testing
System.out.println("String Array:");
for (String finalString : finalStrings) {
System.out.println(finalString);
}
// If you want to convert the values into ints you can do a standard for loop like this
// Lets store the results into an int array
int [] intResults = new int [finalStrings.length];
for (int j = 0; j < intResults.length; j++) {
intResults[j] = Integer.valueOf(finalStrings[j]);
}
// empty line to separate results
System.out.println();
// Printing the array of ints
System.out.println("int Array:");
for (int intResult : intResults) {
System.out.println(intResult);
}
Or in a simplified and more accurate way:
(you can use the example above if you need to understand how it can be done the long way)
int num = 1239012390;
String [] numbers = String.valueOf(num).split("90");
int num1 = Integer.parseInt(numbers[0]);
int num2 = Integer.parseInt(numbers[1]);
System.out.println("1st -> " + num1);
System.out.println("2nd -> " + num2);
I have the following code which splits a string of numbers (separated by a space) and then creates an array of floats :
//Split the string and then build a float array with the values.
String[] tabOfFloatString = value.split(" ");
int length = tabOfFloatString.length;
System.out.println("Length of float string is" + length);
float[] floatsArray = new float[length];
for (int l=0; l<length; l++) {
float res = Float.parseFloat(tabOfFloatString[l]);
System.out.println("Float is " + res);
floatsArray[l]=res;
}
The problem is that some of the values in the string are formatted with scientific notation - e.g they read -3.04567E-8.
What I want to do is end up with a float which does not contain the E number.
I have been reading this thread which suggests that I could use BigDecimal, however am unable to get this to work - is this the best approach or should I try something else ? How to convert a string 3.0103E-7 to 0.00000030103 in Java?
Below is your code slightly modified. As per me this works well and doesn't actually cares he order of the exponents:
public void function() {
String value = "123456.0023 -3.04567E-8 -3.01967E-20";
String[] tabOfFloatString = value.split(" ");
int length = tabOfFloatString.length;
System.out.println("Length of float string is" + length);
float[] floatsArray = new float[length];
for (int l = 0; l < length; l++) {
String res = new BigDecimal(tabOfFloatString[l]).toPlainString();
System.out.println("Float is " + res);
floatsArray[l] = Float.parseFloat(res);
}
}
Accepted answered doesn't work for me, When do
floatsArray[l] = Float.parseFloat(res);
the Float.parseFloat(res) change non scientific anotation into scientific anotation so i had to delete it.
This one worked:
public String[] avoidScientificNotation(float[] sensorsValues)
{
int length = sensorsValues.length;
String[] valuesFormatted = new String[length];
for (int i = 0; i < length; i++)
{
String valueFormatted = new BigDecimal(Float.toString(sensorsValues[i])).toPlainString();
valuesFormatted[i] = valueFormatted;
}
return valuesFormatted;
}
NumberFormat format = new DecimalFormat("0.############################################################");
System.out.println(format.format(Math.ulp(0F)));
System.out.println(format.format(1F));
The float doesn't contain an e, that is just how it is being displayed to you. You can use DecimalFormat to change how it is displayed.
http://ideone.com/jgN6l
java.text.DecimalFormat df = new java.text.DecimalFormat("#,###.######################################################");
System.out.println(df.format(res));
You will notice some odd looking numbers though, due to floating point.