converting float to integer in a special way - java

I am trying to convert float number in Java to integer on the following way:
4.55 = 455
12.45 = 1245
11.1234 = 111234
How can I do it?

One option would be like this:
float number = 4.55f;
int desiredNumber = Integer.parseInt(String.valueOf(number).replaceAll("\\.", ""));
But something like this will only work if the conversion pattern will stay the same. By this I mean the way you want to convert from float to int. Hope this helps.

here is an example
double f1 = 4.5;
String str = new Double(f1).toString();
str = str.replace(".", "");
Integer i = Integer.parseInt(str);
System.out.println(i);

If you want to be able to hanlde arbitrarily large numbers and arbitrarily many decimals, then you can use BigDecimal and BigInteger
BigDecimal number = new BigDecimal(
"5464894984546489498454648949845464894984546489498454648949845464894984546489498454648949845464894984.1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111");
String valueOf = number.toPlainString();
BigInteger desired = new BigInteger((valueOf.replaceAll("\\.", "")));
System.out.println(desired);
Constructor can take double or float if needed
BigDecimal number = new BigDecimal(Double.MAX_VALUE);
BigDecimal number = new BigDecimal(Float.MAX_VALUE);

Something like that :
public int convert( float numbre) {
String nmbre = String.valueOf(numbre).replace(".", "");
return Integer.parseInt(nmbre );
}

You can convert the number to a String, remove the dot, and create a new Long:
private long removeTheDot(Number number) {
return Long.valueOf(number.toString().replace(".", ""));
}
Ka-Bam!

Related

Java code snippet to trim the decimal places in a number based on a condition [duplicate]

I am invoking a method called "calculateStampDuty", which will return the
amount of stamp duty to be paid on a property. The percentage calculation works
fine, and returns the correct value of "15000.0". However, I want to display the value to
the front end user as just "15000", so just want to remove the decimal and any preceding values
thereafter. How can this be done? My code is below:
float HouseValue = 150000;
double percentageValue;
percentageValue = calculateStampDuty(10, HouseValue);
private double calculateStampDuty(int PercentageIn, double HouseValueIn){
double test = PercentageIn * HouseValueIn / 100;
return test;
}
I have tried the following:
Creating a new string which will convert the double value to a string, as per below:
String newValue = percentageValue.toString();
I have tried using the 'valueOf' method on the String object, as per below:
String total2 = String.valueOf(percentageValue);
However, I just cannot get a value with no decimal places. Does anyone know
in this example how you would get "15000" instead of "15000.0"?
Thanks
Nice and simple. Add this snippet in whatever you're outputting to:
String.format("%.0f", percentageValue)
You can convert the double value into a int value.
int x = (int) y where y is your double variable. Then, printing x does not give decimal places (15000 instead of 15000.0).
I did this to remove the decimal places from the double value
new DecimalFormat("#").format(100.0);
The output of the above is
100
You could use
String newValue = Integer.toString((int)percentageValue);
Or
String newValue = Double.toString(Math.floor(percentageValue));
You can convert double,float variables to integer in a single line of code using explicit type casting.
float x = 3.05
int y = (int) x;
System.out.println(y);
The output will be 3
I would try this:
String numWihoutDecimal = String.valueOf(percentageValue).split("\\.")[0];
I've tested this and it works so then it's just convert from this string to whatever type of number or whatever variable you want. You could do something like this.
int num = Integer.parseInt(String.valueOf(percentageValue).split("\\.")[0]);
Try this you will get a string from the format method.
DecimalFormat df = new DecimalFormat("##0");
df.format((Math.round(doubleValue * 100.0) / 100.0));
Double d = 1000d;
System.out.println("Normal value :"+d);
System.out.println("Without decimal points :"+d.longValue());
Use
Math.Round(double);
I have used it myself. It actually rounds off the decimal places.
d = 19.82;
ans = Math.round(d);
System.out.println(ans);
// Output : 20
d = 19.33;
ans = Math.round(d);
System.out.println(ans);
// Output : 19
Hope it Helps :-)
the simple way to remove
new java.text.DecimalFormat("#").format(value)
The solution is by using DecimalFormat class. This class provides a lot of functionality to format a number.
To get a double value as string with no decimals use the code below.
DecimalFormat decimalFormat = new DecimalFormat(".");
decimalFormat.setGroupingUsed(false);
decimalFormat.setDecimalSeparatorAlwaysShown(false);
String year = decimalFormat.format(32024.2345D);
With a cast. You're basically telling the compiler "I know that I'll lose information with this, but it's okay". And then you convert the casted integer into a string to display it.
String newValue = ((int) percentageValue).toString();
You can use DecimalFormat, but please also note that it is not a good idea to use double in these situations, rather use BigDecimal
String truncatedValue = String.format("%f", percentageValue).split("\\.")[0]; solves the purpose
The problem is two fold-
To retain the integral (mathematical integer) part of the double. Hence can't typecast (int) percentageValue
Truncate (and not round) the decimal part. Hence can't use String.format("%.0f", percentageValue) or new java.text.DecimalFormat("#").format(percentageValue) as both of these round the decimal part.
Type casting to integer may create problem but even long type can not hold every bit of double after narrowing down to decimal places. If you know your values will never exceed Long.MAX_VALUE value, this might be a clean solution.
So use the following with the above known risk.
double mValue = 1234567890.123456;
long mStrippedValue = new Double(mValue).longValue();
Alternatively, you can use the method int integerValue = (int)Math.round(double a);
Double i = Double.parseDouble("String with double value");
Log.i(tag, "display double " + i);
try {
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(0); // set as you need
String myStringmax = nf.format(i);
String result = myStringmax.replaceAll("[-+.^:,]", "");
Double i = Double.parseDouble(result);
int max = Integer.parseInt(result);
} catch (Exception e) {
System.out.println("ex=" + e);
}
declare a double value and convert to long convert to string and formated to float the double value finally replace all the value like 123456789,0000 to 123456789
Double value = double value ;
Long longValue = value.longValue();
String strCellValue1 = new String(longValue.toString().format("%f",value).replaceAll("\\,?0*$", ""));
public class RemoveDecimalPoint{
public static void main(String []args){
System.out.println(""+ removePoint(250022005.60));
}
public static String removePoint(double number) {
long x = (long) number;
return x+"";
}
}
This should do the trick.
System.out.println(percentageValue.split("\\.")[0]);
Try:
String newValue = String.format("%d", (int)d);

Java BigDecimal to String

I have below piece of code and my precision is getting lost while converting BigDecimal to String. Any help on this really appreciated.
Expected result : 95.10000000000000%
Actual Result : 95.09999999999999%
public static String getAsString(Object value)
{
if (value == null)
return null;
if (value.toString().length() == 0)
return null;
BigDecimal inputVal = new BigDecimal(value.toString());
if (inputVal == new BigDecimal(0))
return "";
NumberFormat numberFormat = NumberFormat.getPercentInstance(Locale.US);
numberFormat.setMinimumFractionDigits(14);
numberFormat.setMaximumFractionDigits(14);
if (numberFormat instanceof DecimalFormat) {
DecimalFormat df = (DecimalFormat) numberFormat;
df.setNegativePrefix("(");
df.setNegativeSuffix("%)");
}
String num = null;
num = numberFormat.format(new BigDecimal(95.1).divide(new BigDecimal(100)));
return num;
}
With this instance creation
new BigDecimal(95.1)
you are losing some precision. What you actually can do is to use the string constructor:
new BigDecimal("95.1")
Another way for your case is to use the factory methods:
BigDecimal.valueOf(95.1)
BigDecimal.valueOf(100)
Internally these use the string representation of those numbers to create a BigDecimal object.
In this case using the new BigDecimal(double x) and double as an argument and it happens that doubles can't represent x.xxxx exactly. So x.xxxx is "transformed" to the closest possible double, which is x.0000xxxxxxxxxxxzzzzzzzzzzyyyyy and that's what your BigDecimal shows.
So, here the solution could be you can use the String constructor or the valueOf() method, to create the canonical represent of your doubled value.
By changing your line
num = numberFormat.format(new BigDecimal(95.1).divide(new BigDecimal(100)));
to
num = numberFormat.format(BigDecimal.valueOf(95.1).divide(BigDecimal.valueOf(100)));
or
num = numberFormat.format(new BigDecimal("95.1").divide(new BigDecimal("100")));
should give you the correct result.
Try this
BigDecimal inputVal = new BigDecimal(value.toString()).setScale(3, RoundingMode.HALF_UP);
You can use setScale and then convert to a String.
I see you want to print 14 digits, so set the scale to 14, and use rounding up.
BigDecimal inputVal = new BigDecimal(95.10000000000000).setScale(14, RoundingMode.UP);
Then call toString and add the % etc.
You can use string value
num = numberFormat.format(new BigDecimal("95.1").divide(new BigDecimal("100")));

How can I use parseInt for a double?

My program receives some input (a String). It is rather possible that the input is in the form of a double, like "1.5". But I would like to convert it to an integer, so I can end up with just a 1.
First, I tried this:
Integer.parseInt(someString);
But it doesn't work - I'm assuming it is because of the dot . that it can't parse it.
So I thought that maybe the Integer class can create an integer from a double. So I decided to create a double and then make it an int, like this:
Integer.parseInt(Double.parseDouble(someString));
But apparently there is
no suitable method found for parseInt(double)
So, what do you suggest? Are there one-liners for this? I thought about making a method that removes the dot and all characters after it... but that doesn't sound very cool.
It is safe to parse any numbers as double, then convert it to another type after. Like this:
// someString = "1.5";
double val = Double.parseDouble(someString); // -> val = 1.5;
int intVal = (int) Math.floor(val); // -> intVal = 1;
Note that with Java 7 (not tested with earlier JVM, but I think it should work too), this will also yield the same result as above :
int intVal = (int) Double.parseDouble(someString);
as converting from a floating value to an int will drop any decimal without rounding.
use casting.
double val = Double.parseDouble(someString);
int intVal = (int) Math.floor(val);
You've got the Double, I assume, with Double.parseDouble. So just use:
int i = (int) Double.parseDouble(someString);
Try,
int no= new Double(string).intValue();
Try this:
1) Parse the string as double
2) cast from double to int
public static void main(String[] args) {
String str = "123.32";
int i = (int) Math.floor(Double.parseDouble(str));
System.out.println(i);
}

How can i add two double values without exponential in android

Please help me to solve this. I trying to get value from textview and stored as string. Then it converts to double. While converting up to 7 characters functioning normally but if i try to add more than 7 result is 1.23456789E8. Here is my code
String value = tvInput.getText().toString();
\\tvInput is my textView
Double result = 0.0;
Double input1=0.0;
Double input2=0.0;
input=Double.parseDouble(value);
result = input1 + input2;
tvInput.setText(Double.toString(result));
if i give input1 value as 1234567 and input2 as 1234567 i am getting correct result but if give input1 as 12345678 and input2 as 3. the output is 1.2345681E7
The value you get is correct, the issue is with the way you print it.
You're relying on toString for a double output; if you want to guarantee not to have an exponential notation, you should format it using a DecimalFormat, or with String.format;
DecimalFormat myFormatter = new DecimalFormat("############");
tvInput.setText(myFormatter.format(result));
Also see the format documentation
The behavior you describe is consistent with the javadoc. You could use String.format instead.
Either 12345678 and 1.2345678E7 are exactly the same number. No trouble with that
Your trouble is with the representation, if E>6 then toString() use scientific notation. You may want to use NumberFormat for this.
Use String.format: example
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
String i1 = "12345678";
String i2 = "3";
double d1 = Double.parseDouble(i1);
double d2 = Double.parseDouble(i2);
double d = d1 + d2;
System.out.println( String.format("%f", d) );
}
}
Why don't use Integer instead?
String value = tvInput.getText().toString();
\\tvInput is my textView
int result = 0;
int input1 = 0;
int input2 = 0;
input=Integer.parseInt(value);
result = input1 + input2;
tvInput.setText(Integer.toString(result));

Double number's multiplication with out precision and commas

i have an array, a double array like...
Double my_array = new Double[] {6272640.0, 43560.0, 4840.0, 0.0015625, 4046856422.400000095, 40468564.223999999, 4046.856422400, 0.004046856, 1.0, 0.404685642};
and in my program i want to multiply each of that elements with some integer values...
which i accept through a variable n.
i had done it in my program as...
for(int 1=0;i<my_array.length;i++)
{
my_array[i] = n*my_array[i];
}
when i try to print the result, i gets value as exponentials...
like, 3.23E etc etc......
I need the result as double value up to 8 decimal points...
What should i do to get it
You should format your output.
http://docs.oracle.com/javase/tutorial/java/data/numberformat.html (general explanation)
http://download.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html (formatting symbols)
double yourDouble = 0.1234567890;
DecimalFormat myFormatter = new DecimalFormat("0.00000000");
System.out.println(myFormatter.format(yourDouble));
Should print "0.12345678".
try this way
java.text.DecimalFormat df = new java.text.DecimalFormat("###.########"); // define here how much you want precision
for(int i=0;i<my_array.length;i++)
System.out.println(df.format(my_array[i]));
Does
String str = String.valueOf(double d);
solve the problem?
Try this out:
double value = X.XX;
DecimalFormat decimalFormat = new DecimalFormat();
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator('.'); // if needed
symbols.setGroupingSeparator('\u0020'); // if needed
decimalFormat.setDecimalFormatSymbols(symbols);
decimalFormat.setMaximumFractionDigits(8); // or any other
decimalFormat.setMinimumFractionDigits(8); // or any other
decimalFormat.setRoundingMode(RoundingMode.HALF_EVEN); // if needed
return decimalFormat.format(value);
Check this site...
http://www.jguru.com/faq/view.jsp?EID=1307290
I had changed my double array to String array, like
String my_array[];
my_array = new String[] {"1.006944444","6.45160645160", "0.00000326701", "0.0076001595"};
// then used my for loop like
BigDecimal b1 = new BigDecimal(n);
for(int 1=0;i<my_array.length;i++)
{
BigDecimal b2 = new BigDecimal(Double.parseDouble(my_array[i]));
BigDecimal result = b1.multiply(b2);
System.out.println(result.doubleValue);
}
just check it yourself. as i had just described the logic, my for loop had much more to do..

Categories