How can i add two double values without exponential in android - java

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));

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);

converting float to integer in a special way

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!

How to add 0 before decimal

I want to add zero before decimal, if the number starts with decimal itself.
Input: .2345
Output: 0.2345
I'm using DecimalForamtter. I'm avoiding using string appender.
Please suggest.
Thank You
that should give you the expected output:
#Test
public void testFloatLeadingZero(){
float value = .1221313F;
DecimalFormat lFormatter = new DecimalFormat("##0.0000");
String lOutput = lFormatter.format(value);
Assert.assertTrue(lOutput.startsWith("0."));
}
or with String.format:
#Test
public void testFloatLeadingZero(){
float value = .1221313F;
String lOutput = String.format("%.20f", value);
Assert.assertTrue(lOutput.startsWith("0."));
double value2 = .1221313d;
String lOutput2 = String.format("%.20d", value2);
Assert.assertTrue(lOutput2.startsWith("0."));
}
I think you are using Float right? Otherwise you have to replace f with d for Double.
I have used below code and worked in all scenarios. I wanted to get 10 digits including 2 decimal places. It will give me trailing 0s in decimal place also.
DecimalFormat df = new DecimalFormat("00000000.00");
double d1 = 678.90;
System.out.println(df.format(d1));
Output: 00000678.90

cast String with period and comma to int

how to cast String with period and comma to int, like
String a "9.000,00"
int b = Integer.parseInt(a);
when I run this code, I get an error message : Exception in thread "main" java.lang.NumberFormatException: For input string: "9.000,00"
If you want to get as result 900000 then simply remove all , and . and parse it with for instance with Integer.parseInt or Long.parseLong or maybe even better use BigInteger if number can be large.
String a = "9.000,00";
BigInteger bn = new BigInteger(a.replaceAll("[.,]", ""));
System.out.println(bn);
Output: 900000
But if you want to parse 9.000,00 into 9000 (where ,00 part is decimal fraction) then you can use NumberFormat with Locale.GERMANY which uses form similar to your input: 123.456,78
String a = "9.000,00";
NumberFormat format = NumberFormat.getInstance(Locale.GERMANY);
Number number = format.parse(a);
double value = number.doubleValue();
//or if you want int
int intValue = number.intValue();
System.out.println(value);
System.out.println(intValue);
Output:
9000.0
9000
final String a = "9.000,00";
final NumberFormat format = NumberFormat.getInstance(Locale.GERMAN); // Use German locale for number formats
final Number number = format.parse(a); // Parse the number
int i = number.intValue(); // Get the integer value
Reference
To do that, you need to use java.text.NumberFormat and NumberFormat.getInstance(Locale.FRANCE) (or another compatible Locale)
import java.text.NumberFormat;
import java.util.Locale;
class Test {
public static void main(String[] args) throws Exception {
NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
String a = "9.000,00";
a = a.replaceAll("\\.", "");
Number number = format.parse(a);
double d = number.doubleValue();
int c = (int) Math.floor(d);
System.out.println(c);
}
}
prints 9000 as you want ( and now is an int ) !
If I print every intermediate step :
import java.text.NumberFormat;
import java.util.*;
class test {
public static void main(String[] args) throws Exception {
NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
String a = "9.000,00";
a = a.replaceAll("\\.", "");
System.out.println(a); // prints 9000,00
Number number = format.parse(a);
System.out.println(number); // prints 9000
double d = number.doubleValue();
System.out.println(d); // prints 9000.0
int c = (int) Math.floor(d);
System.out.println(c); // prints 9000
}
}
so if Okem you want 9000,00 as you're saying in your comment, you just need
a = a.replaceAll("\\.", "");
System.out.println(a);
which gives you an output of 9000,00
I hope that helps.
Try this -
String a = "9.000,00";
a = a.replace(",","");
a = a.replace(".","");
int b = Integer.parseInt(a);
I think DecimalFormat.parse is the Java 7 API way to go:
String a = "9.000,00";
DecimalFormat foo = new DecimalFormat();
Number bar = foo.parse(a, new ParsePosition(0));
After that, you go and be happy with the Number you just got.
If you want the answer to be 900000 (it doesn't make sense to me, but I'm replying to your question) and put that into an int go with:
int b = Integer.parseInt(a.replaceAll(",","").replaceAll("\\.",""));
as already outlined in the comments.

How to convert a String number to two three decimal places in Java?

I am trying to convert a String number to two decimal places in Java. I saw lot of posts on satckoverflow but somehow I am getting an exception.
String number = "1.9040409535344458";
String result = String.format("%.2f", number);
System.out.println(result);
This is the exception I am getting -
java.util.IllegalFormatConversionException: f != java.lang.String
I would like to have 1.904 as the output. Does anyone know what wrong I am doing here?
You can try using a NumberFormat. For example:
String number = "1.9040409535344458";
NumberFormat formatter = new DecimalFormat("#0.000");
String result = formatter.format(Double.valueOf(number));
System.out.println(result);
Just declare number to be double :
Double number = 1.9040409535344458;
instead of
String number = "1.9040409535344458";
OUTPUT :
1.90
you should first convert the string into double and then change the decimal value
String number = "1.9040409535344458";
double result = Double.parseDouble(number);//converts the string into double
result = result *100;//adjust the decimal value
System.out.println(result);
You are using a format not meant for a String. I would recommend either converting your String to a double or storing it as a double in the first place. Convert the String to a double, and pass that double to String.format.

Categories