How to convert a float to int along with its decimals considered? - java

For example, I am having 12.12 float value I want it to become 1212 an integer value
If I am having 156.2345 I want it to be 1562345.
I have searched a lot but found only rounding and casting to int but no answer for my question.
Moreover, if we have 12.12000 then also I should be getting 1212 only but not 1212000.
The problem is I will be reading double or float from stdinput and I have to convert that to appropriate int as per above rules
Tried Float.intValue() among others, but that gives 12 only

Use following:
floatValue.toString().replaceAll("[0]*$", "").replace(".", "");
First replace will remove all trailing 0s from the float value while second replace will remove the dot.

I am not sure it's a good idea to do this but you can do
double d = 12.12;
long n = Long.parseLong(BigDecimal.valueOf(d).toString().replaceAll("[.,]", ""));
This will drop any decimal places. You can use float and int instead.
If you want 1.0 to be 1 instead of 10, and 10.0 to be 1 instead of 10or 100 you can add
.replaceAll("[0]*$", "")
Tried Float.intValue() among others, But that gives 12 only
As it should. intValue returns the value as an int rounded down.

Here's an alternative approach that multiplies the number by 10 until the remainder division by 1 yields 0:
static long toLong(double d) {
if (d % 1 != 0) {
return toLong(d * 10);
}
return (long) d;
}

Integer.parseInt(Float.toString(value).replaceAll(Pattern.quote("."), ""));
The shortest and safe code.
replaceAll() takes regex as argument, so you must use Pattern.quote();
Integer.parseInt(): Parses an Integer from String. (ex: "123" -> (int)123)
Float.toString(): Converts a Float to String. (ex: 12.34 -> "1234")
replaceAll(String regex, String change_to): Replace all 'regex' to change_to.

Related

How to remove decimal in java without removing the remaining digits

Is there any method to remove the . in java into a double value?
Example :
56.11124
to
5611124
I don't think there's a mathematical way to find out how many decimals there are in a double. You can convert to a String, replace the dot, and then convert it back:
Double.parseDouble(Double.toString(56.11124).replace(".", ""));
Be careful of overflows when you parse the result though!
Here's one way to do it,
First, convert the double to a string. Then, call replace to replace . with an empty string. After that, parse the result into an int:
double d = 5.1;
String doubleString = Double.toString(5.1);
String removedDot = doubleString.replace(".", "");
int result = Integer.parseInt(removedDot);
Obviously, this wouldn't work if the double's string representation is in scientific notation like 5e16. This also does not work on integral double values, like 5, as its string representation is 5.0.
doubles are inaccurate by nature. 5 and 5.0 are the same value. This is why you can't really do this kind of operation. Do you expect different results for a and b?
double a = 5;
double b = 5.0;
If you do, then you can't really do this, since there is no way of knowing what the programmer wrote exactly at runtime.
This might work
class Example {
public static void main(String[] args) {
double val = 56.1112;
while( (double)((int)val) != val )
{
val *= 10;
}
System.out.printf( "%.0f", val );
}
}
Output: 561112
This works by casting the double to int which truncates the floating information 56.11124 => 56. While the values aren't equal you multiply it by the base to push the . out. I don't know if this is the best way.
You can convert to BigDecimal and use the unscaledValue method:
BigInteger unscaled = new BigDecimal(myDouble).unscaledValue();
Depending on your intended output, you might also use BigDecimal#valueof(double) to create the intermediate BigDecimal.
Javadoc for BigDecimal#new(double)
Javadoc for BigDecimal#valueOf(double)
Javadoc for BigDecimal#unscaledValue()
You can convert it to a String and remove the . and convert it back to double something like
double value = 56.11124;
value = Double.valueOf(("" + value).replace(".", "")).doubleValue();
This will return 5611124.0 since its a double you will have the floating point. You can convert it to an int, but you have to take care of the possible overflow. Otherwise it would look like this
int normalized = (int) value;

- Rounding a double up & removing the numbers after a decimal point -

Could someone tell me how I can round a double & then remove the numbers after the decimal places - & then convert this number to a String please?
e.g. start with a double value 55.6666666666667 - round it up to a double value of 56.0000000000 -
or start with 55.333333333333 - round down to a double value of 55.0000000000 -
& then remove the decimal point and trailing zeros - convert to String.
Thanks.
The best way to round a value to the nearest integer is:
int x = (int)Math.round(55.6666666666667);
x will be 56. You can also use Math.ceil() and Math.floor() to round up or down respectively. Finally to make x a string use String.valueOf(). Like this:
String xString = String.valueOf(x);
If you wanted to do it all on one line:
String xString = String.valueOf(Math.round(55.6666666666667));
You can read more about the Math class here and the String class here.
Use the Math.round() function. You can cast it to an int to eliminate the decimal places, or you can use Math.floor() or Math.ceil() to round it down or up before casting.
Assuming that you don't actually want to save the rounded value, but just want to see it as a string, this should do everything you want, where x is the double:
String s = String.format("%.0f", x);

How to cast String with decimal(a.bc) to int(abc) in Java

I want to do some calculation with a list of String:
1.23
4.56
7.89
For accuracy, I want the convert the above String to int:
123
456
789
How to do that?
Sorry for my vague description. What I really need is no matter what the input is, the int value should hold the specific decimal:
Let say I need 4 decimal:
String:1 ; int: 10000
String:1.23 int: 12300
String:1.2345 int:12345
I would strip out the dots then parse as an int:
int i = Integer.parseInt(str.replace(".", ""));
If you need there to always be 3 digits, this approach gets ugly, but doable:
int i = Integer.parseInt((str.replace(".", "") + "00").replaceAll("^(...).*", "$1"));
This avoids the vagaries of the imprecision of double values, which could lead to incorrect results due to truncation when casting from double to int.
Here's an example of imprecision problems:
int i = (int) (100 * Double.parseDouble("1.13")); // 112
This is because:
double d = Double.parseDouble("1.13"); // 112.99999999999999
You can use
long n = Math.round(Double.parseDouble(text) * 100);
This will mean numbers like 0.1 will be 10 not 1 and 1.110 will be 111 not 1110
Let say I need 4 decimal:
String:1 ; int: 10000
String:1.23 int: 12300
String:1.2345 int:12345
needs
long n = Math.round(Double.parseDouble(text) * 10000);
You can replace all dots with empty strings (text.replace(".", "")) and then use Integer.parseInt(text).
For one String, you can do:
private static final BigDecimal ONE_HUNDRED
= new BigDecimal(100);
// In code:
new BigDecimal(inputString).multiply(ONE_HUNDRED).intValueExact();
Note the use of BigDecimal here; a double will NOT do.
Note also that it will work only if the input has at most two decimal digits: if more than that, .intValueExact() will throw an exception (it will also throw an exception if the decimal integer is out of bounds for an int).
Now, it depends on how precise you need to be; this method guarantees the results. The method to remove dots and parse as int is obviously faster ;)
I will suggest you use string.replace and replace all "." with "". Then you can use Integer.parseInt(str) and you will have the result.
str = str.replace(".", "");
int val = Integer.parseInt(str);

How to remove the decimal part from a float number that contains .0 in java

I just want to remove the fractional part of a float number that contains .0. All other numbers are acceptable..
For example :
I/P: 1.0, 2.2, 88.0, 3.56666, 4.1, 45.00 , 99.560
O/P: 1 , 2.2, 88, 3.567, 4.1, 45 , 99.560
Is there any method available to do that other than "comparing number with ".0" and taking substring" ?
EDIT :
I don't want ACTING FLOAT NUMBERs (like 1.0, 2.0 is nothing but 1 2 right?)
I feel my question is little confusing...
Here is my clarification: I just want to display a series of floating point numbers to the user. If the fractional part of a number is zero, then display only the integer part, otherwise display the number as it is. I hope it's clear now..
If android gives you lemons. Dont throw it.
YourFormatedStringNumber = NumberFormat.getInstance().format(myNumber);
makes -> "12.50" to "12.50" and "12.00" to "12"
More here in doc.
You could use a regular expression such as this: \\.0+$. If there are only 0's after the decimal point this regular expression will yield true.
Another thing you could do is something like so:
float x = 12.5;
float result = x - (int)x;
if (result != 0)
{
//If the value of `result` is not equal to zero, then, you have a decimal portion which is not equal to 0.
}
Try:
String.format("%.0f",value);
I can't comment yet so just a heads up.
number value needs to be a double for it to work.
String.format("%.0f", number)
try NumberFormat or even DecimalFormat:
If you want to not show a decimal point where there might be no digits
after the decimal point, use setDecimalSeparatorAlwaysShown.
Well, technically the display part is text, so you could do it with regular expression. If the number matches then use groups to extract the correct part. (I'll update the post with a solution later.)
Alternatively, you could simply go:
if ((int)Math.round(number) == number) {
System.out.println((int) number)
} else {
System.out.println(number)
}
or even:
System.out.println((int) Math.round(number) == number ?
String.valueOf((int) number) : String.valueOf(number));
careful, the String.valueOf() is required, as this does not work. The System.out.println(double) will always get executed, i.e. the below does not work:
System.out.println((int)Math.round(number) == number ? (int) number : number);
try casting int before the float number
I've created this extension method. if amount contains decimal(40.01) it will show decimal other wise it will show only amount(40.00)
input 2000.43, Result = 2,000.43
input 2000.00, Result = 2,000
fun Double.FormattedAmount(): String {
val otherSymbols = DecimalFormatSymbols(Locale.US)
val decimalFormat = DecimalFormat("#,###,###.##", otherSymbols)
return decimalFormat.format(this).toString()
}
Very simple for kotlin
float number = 12.5
number.toInt()

conditions for If Else (with number of decimal places)

Is there a way to execute a piece of code depending on how many decimal places there are in a number. For instance, if the double was just 2.0 i would want to convert it to an integer, but if it were 2.43426 i would want to leave it as a double. Thanks!
Not sure, but would:
double d = 2.0;
if ((long) d == d) {
// then
}
Work for you? That only answers your question in that particular case.
You can specify precision and convert like this:
double precision = 1e-10;
int rounded = Math.round(x);
if (Math.abs(x-rounded) > precision) System.out.print(x)
else System.out.print(rounded);
Convert the double to String
Using regex, find the decimal point and then get the number of characters after that.
Use it in your if-else
A quick and dirty solution would be the following:
double foo = 2.43426;
int count = String.valueOf(foo).split(".")[1].toCharArray().length;
if(count > 1){
// do stuff
}
If this is what you're after:
i would be converting them to strings and writing them out, so i would want it to say 3 instead of 3.0, but not 3 instead of 3.4324.
Then the "correct" way is using DecimalFormat:
DecimalFormat fmt = new DecimalFormat("0.#");
fmt.setMaximumFractionDigits(Integer.MAX_VALUE);
assert "3".equals(fmt.format(3.0));
assert "3.4324".equals(fmt.format(3.4324));
It does, however, localize the decimal separator (I get a comma rather than a dot). If that's an issue, you can just call fmt.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.ROOT)).

Categories

Resources