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.
Related
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]);
}
I have an page object list element called (number_Check) text value = ($479.00/check). I have 3 same values. I need to add them and check it equals to a full number $1437.00 == finalnumber element. Could you help me? I tried with regex. I don't know how to compare to final number.
List<String> mylist = new ArrayList<String>();
String regex = "-?[0-9]+(?:,[0-9]+)?";
Pattern p = Pattern.compile(regex);
for (int i = 0; i < number_check.size(); i++) {
String bvalue = number_check.get(i).getAttribute("text");
String cvalue = number_check.get(1).getAttribute("text");
String dvalue = number_check.get(2).getAttribute("text");
String final = finalnumber.getAttribute("text");
Matcher m = p.matcher(bvalue);
Matcher c = p.matcher(cvalue);
Matcher d = p.matcher(dvalue);
double sum = 0;
while (m.find()) {
mylist.add(m.group(0));
mylist.add(c.group(0));
mylist.add(d.group(0));
sum += Double.parseDouble(m.group(0) + c.group(0) + d.group(0));
}
System.out.println(sum);
}
There are several problems with the code and you don't need regex to do this. Here's a simpler version.
double actual = 0;
for (int i = 0; i < number_check.size(); i++)
{
actual += getDoubleFromString(number_check.get(i).getAttribute("text"));
}
double expected = getDoubleFromString(finalnumber.getAttribute("text"));
Assert.assertEquals(actual, expected);
...and since you are likely to reuse this a lot, I wrote a function to convert the string to a double after stripping out the non-numbers.
public static double getDoubleFromString(String s)
{
return Double.parseDouble(s.replaceAll("[^\\d.]", ""));
}
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 am trying to split number but don't know how to do this.
I referred this link.
https://stackoverflow.com/a/12297231/1395259
Suppose I have a number 12345678.
using above link I am splitting by 3 places.So the output becomes 123 456 78.
But I want it as 12 345 678 And I want to take the string that was split in the form 12.345.678 .
Can anybody help me please??
java.text package provides all reasonable options for formatting numbers
DecimalFormat f = new DecimalFormat("#,###");
DecimalFormatSymbols fs = f.getDecimalFormatSymbols();
fs.setGroupingSeparator('.');
f.setDecimalFormatSymbols(fs);
String s = f.format(12345678);
System.out.println(s);
output
12.345.678
using DecimalFormat directly is very flexible, but typically we can use a shorter version
String s = NumberFormat.getNumberInstance(Locale.GERMAN).format(12345678);
which produces the same string
12.345.678
Different countries have different rules for formatting numbers (and dates). Usually we want our programs to be internationalized / localized and use default locale version
NumberFormat.getNumberInstance().format(number);
One lazy way is to reverse the string, apply above method, and then reverse it again.
You can use StringBuffer's Reverse Function, as shown in Reverse each individual word of "Hello World" string with Java
12345678
87654321
876 543 21
12 345 678
I am assuming of course that you want to split by 3s and the group with <3 digits left appears in the start rather than the end as in the method you link.
The not so lazy way would be to use string length to adapt the method you link to start with length%3 characters.
Using the solution from your link i would rephrase that as following (TESTED!):
public String[] splitStringEvery(String s, int interval) {
int arrayLength = (int) Math.ceil(((s.length() / (double)interval)));
String[] result = new String[arrayLength];
int j = s.length();
int lastIndex = result.length;
for (int i = lastIndex - 1; i > 0; i--) {
result[i] = s.substring(j - interval, j);
j -= interval;
} //Add the last bit
result[0] = s.substring(0, j);
return result;
}
Here is a method that splits an int value and returns an String in the specified format:
public static String split( int n ) {
String result = "", s = Integer.toString( n );
while ( s.length() > 3 ) {
result = s.substring( s.length() -3, s.length() ) + ((result.length() > 0)? "." + result : "" );
s = s.substring( 0, s.length() -3 );
}
return s + "." + result;
}
Input:
12345678
Output:
12.345.678
If it's a String, use StringBuilder or StringBuffer. Here's the code:
public class SplitNumber {
public static void main(String[] args){
int number = 12345678;
String numberStrBefore = Integer.toString(number);
StringBuffer numberStrAfter = new StringBuffer();
numberStrAfter.append(numberStrBefore.charAt(0));
numberStrAfter.append(numberStrBefore.charAt(1));
numberStrAfter.append('.');
numberStrAfter.append(numberStrBefore.charAt(2));
numberStrAfter.append(numberStrBefore.charAt(3));
numberStrAfter.append(numberStrBefore.charAt(4));
numberStrAfter.append('.');
numberStrAfter.append(numberStrBefore.charAt(5));
numberStrAfter.append(numberStrBefore.charAt(6));
numberStrAfter.append(numberStrBefore.charAt(7));
System.out.println("Number Before: " + numberStrBefore);
System.out.println("Number After: " + numberStrAfter.toString());
}
}
And here is the same thing with a method:
public class SplitNumber {
public static void main(String[] args){
int number = 12345678;
int[] split = {2,3,3}; //How to split the number
String numberStrAfter = insertDots(number, split);
System.out.println("Number Before: " + number);
System.out.println("Number After: " + numberStrAfter);
}
public static String insertDots(int number, int[] split){
StringBuffer numberStrAfter = new StringBuffer();
String numberStr = Integer.toString(number);
int currentIndex = 0;
for(int i = 0; i < split.length; i++){
for(int j = 0; j < split[i]; j++){
numberStrAfter.append(numberStr.charAt(currentIndex));
currentIndex++;
}
numberStrAfter.append('.');
}
numberStrAfter.deleteCharAt(numberStrAfter.length()-1); //Removing last "."
return numberStrAfter.toString();
}
}
This version, with the method, allows you to split any number into any format that you want, simply change the "split" variable into the format that you want to split the string into. (Ex: Splitting 12345678 into: 1.1234.5.67.8 would mean that "split" must be set to {1,4,1,2,1}).