How to Avoid Scientific Notation in Double? - android

Here is my simple code
#Override
public void onClick(View v) {
try {
double price = Double.parseDouble(ePrice.getText().toString());
double percent = Double.parseDouble(ePercent.getText().toString());
double priceValue = price * percent/100.0f;
double percentValue = price - priceValue;
moneyToGet.setText(String.valueOf(priceValue));
moneyToPay.setText(String.valueOf(percentValue));
moneyToGet.setText("" + priceValue);
moneyToPay.setText("" + percentValue);
// catch
} catch (NumberFormatException ex) {
// write a message to users
moneyToGet.setText("");
}
}
});
This is a simple code for Percentage Calculator.
What I want is to avoid the Scientific Notation in my Calculator cause I don't want to explain to user what is Scientific Notation.
For example if I want to calculate 100,000,000 and cut 50% of it, it Should give me 50,000,000 which is giving me 5.0E7 And in my case this doesn't make any sense to the user. And of course I know both results are correct.
Thanks in Advance.

Check answer here. You can write
moneyToGet.setText(String.format("%.0f", priceValue));

You can try this DecimalFormat
DecimalFormat decimalFormatter = new DecimalFormat("############");
number.setText(decimalFormatter.format(Double.parseDouble(result)));

I would suggest using BigDecimals instead of doubles. That way you will have a more precise control over your calculation precision. Also you can get a non-scientific String using BigDecimal.toPlainString().

DecimalFormat decimalFormatter = new DecimalFormat("##.############");
decimalFormatter.setMinimumFractionDigits(2);
decimalFormatter.setMaximumFractionDigits(15);
This option will help you ##.## suffix 0 before decimal, otherwise output will be .000
btc.setText(decimalFormatter.format(btcval));
use this for displaying content

Use NumberFormater like
NumberFormat myformatter = new DecimalFormat("########");
String result = myformatter.format(yourValue);

Related

Android slpit string doubleparse and pass it to a method that converts degrres to decimal

I have a android method that converts degrees minutes and seconds to decimal. I am getting the text from edittext split it and convert it to double array before I pass it to the method. Then I wanted to get the double returned in a decimal form to be displayed in the original edittext as string. Here is the code,
public double DegreeToDecimal(double d, double m, double s)
{
double decimal;
decimal = d + m/60 + s/3600;
return decimal;
}
try
{
String string = dtod.getText().toString();
String[] s = string.split(":");
String decimal;
double d = DegreeToDecimal(Double.parseDouble(s[0]), Double.parseDouble(s[1]), Double.parseDouble(s[2]));
decimal = String.valueOf(d);
dtod.setText(decimal);
}catch (Exception e){
e.printStackTrace();
}
When I do this on a button click, nothing happens. The Logcat doesn't show anything and the code is simply ignored. What am I doing wrong?
Thanks for the help.
Your code formatting is all over the place and hard to read, please try to use correct indentation next time!
From the code you posted it's hard to tell what happens. If Logcat doesn't show any stacktraces like you said, and if your code is "ignored" as you say then my guess is that it doesn't get called.
Did you attach an OnClickListener to that button?
Otherwise try to log something between your lines or use a debugger to find out what really happens!

Get EditTextValue and parse it into a decimal with only one digit for integer part

I'm having an issue when I get a whole number from an EditText and try to change that to a decimal so I can use it for calculations. Could someone explain how to do this?
For Example. if someone was to enter 120 into the EditText and I got the integer from it, how would I then change that integer of 120 into 1.20 and continue calculations with it?
Thanks!!
EditText myEditText = (EditText)findViewById(R.id.YOUR_EDIT_TEXT_ID);
String numberAsString = myEditText.getText().toString();
double myDecimal;
try {
myDecimal = Double.parseDouble(numberAsString);
if (myDecimal >= 10)
{
int digits = 1 + (int)Math.floor(Math.log10(myDecimal));
myDecimal = myDecimal / ((Math.pow((double)10, ((double)digits) - 1)));
System.out.println(myDecimal);
}
} catch (NumberFormatException e) {
//handle exeption
e.printStackTrace();
}
You need to get the contents from your EditText as a string, and from there you can parse it into an integer. This is done like so:
int wholeNum = Integer.parseInt(yourEditText.getText().toString());
int three = Integer.parse("3");
I know you can use this to parse a string into an integer, there is probably a parse method in double aswell!
Check this also :
Convert a String to Double - Java
+1 to anthony for answering 1 minute before me haha

Google Maps automatically convert period (.) into comma (,) from my Intent URI

I'm calling Google Maps Intent from my activity with this code found on StackOverflow:
final String uriContent = String.format(Locale.ENGLISH, "http://maps.google.com/maps?q=loc:%s", pCoordinate);
final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uriContent));
pContext.startActivity(intent);
where pCooriante contains entirely address such as 1.23456,7.8901.
It works well when my phone is using English as its language, but when I change it to French or Vietnamese (which use comma , as its number decimal seperator), it can't work anymore, because the query proceeded by Google Maps look like: 1,000,2,000 (it is shown in the search bar, and after that, a message like Cannot find 1,0000,2,0000 appears), although the exact URI I sent to the intent is 1.000,2.000 (the coordinate is converted to String to prevent Locale problems, and therefore the Locale.ENGLISH in String.format is more or less just abundant).
In short, Uri.parse(uriContent) return exactly the request with the query is 1.000,2.000, but Google Maps itself changed it. However, the code for direction works well with either Locale:
final String uriContent = String.format(Locale.ENGLISH, "google.navigation:q=%s", pCoordinate);
final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uriContent));
pContext.startActivity(intent);
Is there anyway to prevent the conversion of Google Maps? If I use geo:<coordinate>, it's fine, but I need a marker at that position.
Addional information:
This code final String uriContent = String.format("geo:0,0?q=%s&z=19", pCoordinate); doesn't work too, the periods are converted into commas.
This code final String uriContent = String.format("geo:%s?q=%s&z=19", pCoordinate, pCoordinate); can bring the map center to the coordinate, but still cannot put the marker there, and with the error "Cannot find 'coordinate with periods replaced by commas'"
I am using a temporary solution to this problem, by converting the decimal form of coordinates to degree one. (For example, instead of sending 10.768717,106.651488, I send 10° 46' 7.3812",106° 39' 5.3568"). The conversion is just simple mathematics operation.
However, there was a problem with Java float and double precision, and that was a lot of distance when sending to Google Maps. Therefore I change my input data, convert data using C#'s decimal and my Android app just use it without manupilating anything. Here is the convesion (C#) code:
protected String convertDecimalToDegree(decimal pDecimal)
{
int degree = (int)Math.Floor(pDecimal);
pDecimal -= degree;
pDecimal *= 60;
int minute = (int)Math.Floor(pDecimal);
pDecimal -= minute;
pDecimal *= 60;
return degree + "° " + minute + "\' " + pDecimal + "\"";
}
Usage:
String[] coordinates = shop.MapCoordination.Split(',');
decimal n1 = Decimal.Parse(coordinates[0]);
decimal n2 = Decimal.Parse(coordinates[1]);
shop.MapCoordination = this.convertDecimalToDegree(n1) + "," + this.convertDecimalToDegree(n2);
I will mark this as answer for now, but I appreciate any solution without having to convert to this form.
You can use the following snippet to solve the problem
public String getCoordinates(String coordinates){
if(Locale.FRANCE == Locale.getDefault()){
Pattern p = Pattern.compile(",.*?(,)");
Matcher m = p.matcher(coordinates);
if (m.find( )) {
int index = m.end(); //gets the second comma position
String str1 = coordinates.substring(0,index-1);
String str2 = coordinates.substring(index,coordinates.length());
NumberFormat nf = NumberFormat.getInstance(Locale.FRANCE);
try {
str1 = nf.parse(str1).toString();
str2 = nf.parse(str2).toString();
} catch (ParseException e) {
e.printStackTrace();
}
return str1+","+str2;
}
}
return coordinates;
}
Updating the Google Maps app to the latest version (7.2.0) seems to fix the issue.
in Xamarin.Android:
using System.Globalization;
Android.Net.Uri.Parse("http://maps.google.com/maps?daddr=" + myLatitude.ToString(CultureInfo.InvariantCulture) + "," + myLongitude.ToString(CultureInfo.InvariantCulture)));

Rounding up decimal in EditText

I'm trying to figure out how to round up the total to two decimal places. The total is an EditText. I can't get it to narrow down to just two decimal places. What wrong with it? Thanks for your help.
public void macro() {
caloriesTotal = Double.parseDouble(calories.getText().toString());
total = (caloriesTotal * .20)/9;
DecimalFormat round = new DecimalFormat ("###.##");
round.format(total);
carbsTotal = (caloriesTotal * .40)/4;
proteinTotal = (caloriesTotal * .40)/4;
fat.setText(Double.toString(total));
carbs.setText(Double.toString(carbsTotal));
protein.setText(Double.toString(proteinTotal));
}
Try this.
fat.setText(Double.valueOf(round.format(total)));
When you convert any number upto N number of decimal digit then you need to store that value in any variable or directly show like as above i mentioned.
Simply format() should do for you,
DecimalFormat round = new DecimalFormat ("###.##");
String formatted = round.format(double_value);
fat.setText(formatted);
You can use String.format("%.2f", d), your double will be rounded

Add current value of EditText to a set value

public void onClick(View v)
{
s.setText(s.getText().toString() + .5);
}
I want to have the value that is currently in s (EditText) to be .5 higher than it was before I clicked the button, I am a completely new to java and am unsure how to make this work. Any help is good help, Thank you in advance.
Edit: as others have mentioned, doubles are usually better than floats.
getText().toString() needs to be turned into a numeric value before it's possible to add .5
try {
double currentValue = Double.parseDouble(s.getText().toString())
double newValue = currentValue + 0.5;
s.setText(newValue.toString());
} catch (NumberFormatException e) {
// text in EditText was not a parsable number
...
}
float can cause unwanted representation. So if you want exact representation, try BigDecimal.
Modify your code
s.setText( new BigDecimal(s.getText().toString()).add(new BigDecimal( "0.5")).toString());
First of all use Double.parseDouble() method to convert string to double.
double val=Double.parseDouble(s.getText().toString()) + 0.5;
s.setText(String.valueOf(val);

Categories

Resources