This question already has answers here:
How to Replace dot (.) in a string in Java
(4 answers)
Closed 8 years ago.
I am reading in java inputs in format below
2499.873639
32.374242
0.610059
...
Now i want to get rid of the decimal place and have them in this format
2499873639
32374242
610059
...
I have this code which does it for smaller number for not for larger numbers. The Larger numbers become negative (i think this overflowing) and giving it junk values.
BigDecimal b = new BigDecimal(a).multiply(new BigDecimal("1000000.")
If i increase the 0's by another two
BigDecimal b = new BigDecimal(a).multiply(new BigDecimal("100000000.")
It works for larger numbers but not smaller numbers. In short of having a bunch of if's is there anyway to fix this issue?
Use this :
BigDecimal b = new BigDecimal(a.toString().replace('.', ''));
String formattedInput = (String.valueOf(input)).replace(".", "");
You can do this with String replacement functions.
public static BigDecimal noDecimal(BigDecimal b) {
return new BigDecimal(b.toPlainString().replace(".", ""));
}
If you already have a String rather than a BigDecimal, this can be simplified to this:
public static BigDecimal noDecimal(String s) {
return new BigDecimal(s.replace(".", ""));
}
Convert the double to String, if it is not.
Then use String.replace('.', '');
Then Convert back to int or long, if necessary.
Related
This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 1 year ago.
I have a very weird result when I'm using my function and I think that I'm missing something with the rounding and double in java.
For example, when I provide the value 00159,300 for number and 100 for conversion I have 15930,000000000002 which is not possible!
public static String convertMultiply(String number, String conversion) {
number=number.replace(",", ".");
BigDecimal res=BigDecimal.valueOf(Double.valueOf(number)*Integer.valueOf(conversion));
res=res.stripTrailingZeros();
return res.toPlainString().replace(".", ",");
}
thanks in advance!
Double is an approximation of decimal values in Java. Instead, replace your line using double with:
BigDecimal res = (new BigDecimal(number)).multiply(new BigDecimal(conversion));
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.
This question already has answers here:
Best way to parseDouble with comma as decimal separator?
(10 answers)
Closed 4 years ago.
I have this String -> "100,24" and I want join in the var Java type float
But when I have the parse, I get error.
article.cost((Float.parseFloat(array.get(y))));
I need help, ty.
The number format must contain dot(.) instead of comma(,). That's why you get the exception. However, you can also use parseFloat with String's replace method to convert float by using comma.
class NumberTest {
public static void main(String[] args) {
String y = "100,24";
float num = Float.parseFloat(y.replace(',','.'));
System.out.println(num);
}
}
Your issue is the comma, "100,24", that string is not a valid float. So an error will be thrown if you try converting it to one. However if this is what you intended "100.24" that should fix your problem, because that is a valid float type.
So what you do is replace the ',' with a '.' and then try converting. i.e.
String floatStr = "100,24".replace(",", "."); // Change to a correct float value
float newFloat = Float.parse(floatStr); // parse and get your new float
This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 7 years ago.
Is it possible to change a float value to a String? If possible, is it also possible to converting it to a String while rounding the number to the nearest integer?
For example if I have a float such as 2.335 then, can I change it to a String of value "2.335" or "2" (by rounding it)?
Use java Float class:
String s = Float.toString(25.0f);
if you want to round down a number, simply use the Math.floor() function.
float f = 2.9999f;
String s = Float.toString(Math.floor(f));//rounds the number to 2 and converts to String
first line rounds the number down to the nearest integer and the second line converts it to a string.
Another way of doing this is using the String.valueOf(floatNumber);
float amount=100.00f;
String strAmount=String.valueOf(amount);
To do this you can simply do
float example = 2.335
String s = String.valueOf(Math.round(example));
To convert a float to a String:
String s = Float.toString(2.335f);
Rounding can be done via
String.format("%.5g%n", 0.912385);
which returns 0.91239
For a more elaborate answer, see Round a number in Java
Your first requirement can be fullfilled with String.valueOf
float f = 1.6f;
String str = String.valueOf(f);
For roundoff you can use Math.round and not Math.floor. As Math.floor will convert 1.6 to 1.0 and not 2.0 while Math.round will roundoff your number to nearest integer.
This question already has answers here:
How to nicely format floating numbers to string without unnecessary decimal 0's
(29 answers)
Closed 7 years ago.
If I have a double storing 10.0 what is the best way to convert it to string 10?
Currently I do:
if (object.getValue() > 9.999) {
someObject.setText(String.format("%d", new Double(object.getValue()).intValue()));
}
else {
//use amount as is
}
Update
These are class grade scores. I only care for a good coding style for checking out if a double is 10.0 and only then convert it to the string “10”. Don’t care about any other number
If that is all you want to do you can do like this:
double number = 10.0;
String output = ("" + (int)number);
System.out.println(output);
The easiest way will be by doing this.
double d = 10.0
String str = String.valueOf(d);
System.out.println(str.substring(0,str.indexOf(".")));
Since we are dealing with double, rounding off can be done. Refer this SO
Try this. I think it should work.
String s=String.valueOf(10.0);
s=s.replace(".0","");
System.out.println(s);
try this:
double d = 10;
System.out.println(new BigDecimal(d).setScale(0, RoundingMode.HALF_UP).toPlainString());
will print only 10 without trailing zeros, or you can change the scale if you wish.
The advantage over casting to int is that, there is rounding, and 9.9 will be rounded to 10, while cast to int will give 9.
If you know the string, you can simply substring it until the dot:
String s = "10.0";
System.out.println(s.substring(0, s.indexOf('.')));
If you want to manipulate it as a double (I don't really see why, though), you can try something like:
System.out.println(String.format("%d", (int)Math.floor(new Double("10.0"))));
There are plenty of ways, of course. I think overall your best bet is with a substring, but I'm not sure what your needs are.
Hope this helps :)
UPDATE after question clarification:
If all you're interested is checking the value of a double (assuming of course, object.getValue() is a double), just check:
if (object.getValue() >= 10)
It will cover whatever you need and you can then print a simple "10" string if needed.
You could compare with double 10.00 as in:
final double TEN_DOUBLE = 10.00;
double ten = 10.00;
double nineAndSomething = 9.10;
System.out.println("Formatted:" + ((ten == TEN_DOUBLE) ? "10" : ten));
System.out.println("Formatted:" + ((nineAndSomething == TEN_DOUBLE) ? "10" : nineAndSomething));
This gives you the following output:
Formatted:10
Formatted:9.1