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

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.

Related

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.

Converting BigDecimal to double value

I want to ask how to transform all my String to double with exponential.
when I use the string that length is over seven it's doing fine .
new BigDecimal("12345678").doubleValue() => 1.2345678E7
but seven and under I can't export exponential number.
new BigDecimal("1234567").doubleValue() => 1234567.0
what I want is like 1.234567E6.
Is there any way to do this? I've been searching for a while ,but got nothing.
The problem is the type I return must be double . After transforming the value under seven I can only get the value without exponential.
double test = new BigDecimal("1.234567E6").doubleValue() ;//output 1234567.0
but I need it to be 1.234567E6 and return to caller. Is that Impossible?
You should know that 1.2345678e7 and 12345678.0 are exactly the same value, only with different textual representations. You could represent 1234567.0 as 1.234567e6 too. Also exactly the same double, just a different way of writing it out.
The default output shows values with more than a certain number of significant digits in exponential format ("e-form"), otherwise as plain decimal format.
So you may want to change the formatting of the doubles you receive. This can be done with e.g. DecimalFormat or String.format() or similar. That does not change the doubles, only the way they are presented in a string.
For your problem, you want to convert the value to the BigDecimal with exponential, you can use the DecimalFormat. You can also change the scale for the output value digits.
import java.math.*;
import java.text.*;
public class HelloWorld{
public static void main(String []args){
double a = new BigDecimal("1234567").doubleValue();
String b;
System.out.println(a);
NumberFormat formatter = new DecimalFormat("0.0E0");
formatter.setRoundingMode(RoundingMode.DOWN);
formatter.setMinimumFractionDigits(5); //<---Scale
b = formatter.format(a);
System.out.println(b);
}
}
The output will be like:
1234567.0 //Unformatted Value
1.23456E6 //Formatted Value
See the section about Scientific Notation in java.text.DecimalFormat.
For example,
DecimalFormat scientificFormat = new DecimalFormat("0.###E0");
System.out.println(scientificFormat.format(BigDecimal.valueOf(123456L)));
System.out.println(scientificFormat.format(BigDecimal.valueOf(1234567L)));
scientificFormat.setMinimumFractionDigits(10);
System.out.println(scientificFormat.format(BigDecimal.valueOf(12345678L)));
would give you
1,235E5
1,235E6
1,2345678000E7
Change the pattern to match what you're looking for.

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 split a string without using array data structures?

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;

BigDecimal() omitting leading zero

How I can store the BigDecimal() same as input?
I need to store real numbers using BigDecimal() which may contain following:
02.34
0.12
.12
0
000.000
I used the following approach :
Scanner sc= new Scanner(System.in);
int n=sc.nextInt();
BigDecimal[] amount = new BigDecimal[n];
for(int i=0;i<n;i++) {
amount[i]=sc.nextBigDecimal();
}
But while printing, it prints formatted. Like this:
2.34
0.12
0.12
0.000
0
I want it should be same as inputted. Therefore please let me know that how could I manage to store inputs intact.
the following code should solve your problem, Keep your string as is and convert it into BigDecimal only when you are comparing
Arrays.sort(s, Collections.reverseOrder(new Comparator<String>() {
#Override
public int compare(String a1, String a2) {
BigDecimal a = new BigDecimal(a1);
BigDecimal b = new BigDecimal(a2);
return a.compareTo(b);
}
}));
Since input is originally a string, the only way to store it intact is to store it as a String.
If you later need to do some math on the numbers, convert them then. You could also possibly store them as both String and BigDecimal in an object.
If you want to store input intact, store it as a String. This is exactly the built-in type dedicated to storing character sequences exactly as entered.
BigDecimal, on the other hand, has a numeric representation with no mechanism for storing its decimal input. In fact, you can initialize BigDecimal without providing a decimal representation at all - e.g. through a sequence of arithmetical operations, in which case the initial representation would not be applicable at all.
If you need to do this in many places, make a class for it. Store the original string, along wit BigDecimal that it represents. This way you would be able to do the conversion only once, and keep the original representation along with it:
class OrigBigDecimal {
private String orig;
private BigDecimal val;
public OrigBigDecimal(String s) {
orig = s;
val = new BigDecimal(s);
}
public String toString() { return s; }
public BigDecimal getVal() { return val; }
}
There are a number of ways to approach this:
1- You can create a small elegant object that has 2 variables, a BigDecimal and a string, and its constructor takes the input as a string, store it in a string and parse it and store it in the BigDecimal.
2- You can configure the BigDecimal output format per input:
Format of BigDecimal number
Format a BigDecimal as String with max 2 decimal digits, removing 0 on decimal part

Categories