How to split a string without using array data structures? - java

Say I have the String, "525.005"
I want to be able to set variable references for the numbers before the decimal (525) and after the decimal (005), however I'm NOT allowed to use arrays. String methods are allowed and indeces. I've seen other questions, and all of them suggest using arrays. Is there a way using a loop?
before = "525"
after = "005"

Parse it to a double.
Modulo your double by 1.0 to get the decimal value, subtract that from original value to get interger part.
String myString="525.005";
double StringAsDouble=parseDouble(myString);
double decimalPart=StringAsDouble % 1.0;
double integerPart=StringAsDouble - decimalPart;

Related

How to change decimal value string into int without loosing decimal values?

I am working on a pretty old Java application and I can not change Integer field to something else which can hold decimal values, so I need to convert some decimal string like "100.00", "3.33" "33.44" to Integer without loosing fractional values.
#Test
public void NumberFormatTest(){
String stringValue = "100.00";
int testTest = ? //what I can do here to get exact 100.00 in testTest variable ?
log.info("outPutValue {} ", testTest);
}
Currently its using Integer.parseInt(stringValue) and this is throwing
java.lang.NumberFormatException: For input string: "100.00"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
I am working on pretty old java code application and I can not change Integer field to something else which can hold decimal values
That is because int can only hold whole numbers. For decimal values you need to use float or double:
String s = "3.33";
double d = Double.parseDouble(s);
Alternatively, you might want to look into BigDecimal. Depending on your exact needs, this might be a better fit.
p.s. int, float and double are primitive types. Integer, Float and Double are class wrapper for those types. These are two different things. I recommend you read more about these differences to gain a better understanding.

Java float to string conversion with trailing zeros [duplicate]

This question already has answers here:
Java keep trailing 0 in float operations
(3 answers)
Closed 4 years ago.
I have a requirement where I am getting a float value in java like the one below
1.1
1.10
10.10
when I convert this to string, I want it to be in the same way as
"1.1"
"1.10"
"10.10"
however, when I use the following method,
float fa = 25.50f;//Float.parseFloat("25.5");
String s = Float.toString(fa);
System.out.println(s); // i want the output to be 25.50, but it gives me 25.5
the result turns out to be the following
"1.1"
"1.1"
"10.1"
can somebody advise me how to get 1.10 as "1.10" with the zero in java
If you want it to store the whole number, why don't you just use a String?
I guess if you are getting "1.10" from somewhere, you are getting it as a String (or you would be getting just a "1.1").
There isn't (necessarily) a float value like 10.10f. There might be, but thing is: when you write down a float literal, you shouldn't expect that it really looks like the value you put down.
Only when representing numbers as strings you can uphold such requirements regarding formatting.
In other words, you probably should read this for example.
How it is printed is determined by how you format a number, the float is just a value, and it's actual representation is binary, not decimal.
String s = String.format("%.2f", 25.5f); // 25.50
I highly recommend using double which is simpler to use, and half a trillion times more accurate.
If your float value comes from String I suggest below solution:
public static void main(String[] args) {
String floatValue = "25.20";
String[] splittedFloat = floatValue.split("[.]");
int numberOfDecimalPlaces = splittedFloat[1].length();
float value = Float.valueOf(floatValue);
System.out.printf("%." + numberOfDecimalPlaces + "f\n", value);
}
First you declare your value as String. Then split it with "dot" and check the length of decimal places. Then you parse it into your float value and you do whatever you want with this value. And finally you cat print it with format like previous because you have number of decimal places of this float value.
The output of this code is:
25.20
There is no way to hold 25.20 value in float because the actual value is 25.2 and that 0 is formatting.

Bigdecimal Not giving exact output in Java

Im adding three big decimals here, but it should give me accurate answer. I'm having two strings here and then converting to big decimal. Please dont ask why Im using strings. There is some business where I will get these values as string then I need to convert. Please find the code
BigDecimal a= new BigDecimal(100.05); --> This value I receive from web service. Its a decimal value from the service.
String b= "100.05";
String c= "200.03";
System.out.println(a.add(new BigDecimal(b).add(new BigDecimal(c))));
Output it gives
400.1299999999999971578290569595992565155029296875
Where as it should be 400.13
The problem is your use of new BigDecimal(100.05). The value of a is then 100.0499999999999971578290569595992565155029296875.
If you had specified that value as a string instead, all would be well:
BigDecimal a = new BigDecimal("100.05");
String b = "100.05";
String c = "200.03";
System.out.println(a.add(new BigDecimal(b).add(new BigDecimal(c))));
// Output: 400.13
If you only have the input as a double, you can use BigDecimal.valueOf(double) instead of calling the constructor:
BigDecimal a = BigDecimal.valueOf(100.05); // a is now exactly 100.05
Compare the BigDecimal(double) documentation:
Translates a double into a BigDecimal which is the exact decimal representation of the double's binary floating-point value. (...)
With that of BigDecimal.valueOf(Double):
Translates a double into a BigDecimal, using the double's canonical string representation provided by the Double.toString(double) method.
Note: This is generally the preferred way to convert a double (or float) into a BigDecimal, as the value returned is equal to that resulting from constructing a BigDecimal from the result of using Double.toString(double).
new BigDecimal(100.05)
This gives 100.0499999999999971578290569595992565155029296875, because 100.05 cannot be represented exactly as a double.
You have to use string here as well:
new BigDecimal("100.05")
As you get this value from a web-service, you probably convert it from a String to a float/double. If this is the case, just skip that conversion step.
If your web-service stub maps the return value to float/double, you can consider mapping it to a String directly and then feed it to BigDecimal constructor, like this:
double v = 100.05; // Value from web service
BigDecimal a= new BigDecimal(String.valueOf(v));
String b= "100.05";
String c= "200.03";
System.out.println(a.add(new BigDecimal(b).add(new BigDecimal(c))));
Live Example
That works because the string will only contain as many digits as are needed to differentiate the almost-100.05 value from the next value on either side that can be represented, and so we get the string "100.05", which then BigDecimal can process correctly.
You can format the answer to Decimal places using String.format and specifiying how many digits.
System.out.println(String.format("%.2f", a.add(new BigDecimal(b).add(new BigDecimal(c)))));

How to a parse a string into a float with three decimal points in java

I know there is a way of forcing a float to have 3 decimal points, but how do I make a string representation "4.00000009" retain 3 decimal points after I turn it into a float? Float.parseFloat() rounds it to 4.0. Not using extra libraries would be ideal.
If you're guaranteed that the String is properly formatted, you can take a substring based on the index of the decimal.
Alternatively, you can parse it, multiply by a thousand, round it, and divide it by a thousand.
However, this is going to be bad for you in the long run. Floating point numbers don't fare so well when exact values are needed. Consider BigDecimal instead.
This utility method takes a String and turns it into a float with 3 decimals places:
public static float getFloat(String s) {
BigDecimal decimal = new BigDecimal(s);
decimal = decimal.setScale(3, RoundingMode.HALF_UP);
return decimal.floatValue();
}

Android multiplying double with int [java]

I have a double value a = 0.00059
and an Integer value which gets incremented and multiplied with the double value (say b = 1)
when I set the answer to the textview
//for b = 1
view.setText(((double)(a*b)));
the answer I get is " 5.9E-4 " however it should be 0.00059.
am I multiplying the values correctly.?
In addition to the other answers provided, you can use a formatter:
NumberFormat formatter = new DecimalFormat("#.#####");
view.setText(formatter.format(a*b));
You are multiplying them correctly. The values 5.9E-4 and 0.00059 are equivalent, mathematically and programmatically. The representation 5.9E-4 is like scientific notation, i.e. 5.9x10^(-4) is equivalent to 0.00059.
You get the same value as you want to get, but formatted in a scientific notation. What you need to do is to explicitly convert it to String:
view.setText(String.format("%f", a*b));
And you could eventually specify the number of decimal places to print after the decimal separator in this way:
// displays two digits after the decimal separator
view.setText(String.format("%.2f", a*b));

Categories