I will Format a Floating Point Number in android with 2 Digits after the point.
I search for a Example but i dinĀ“t find one.
Can some one help me.
float f = 2.3455f;
String test = String.format("%.02f", f);
You can also use DecimalFormat
float f = 102.236569f;
DecimalFormat decimalFormat = new DecimalFormat("#.##");
float twoDigitsF = Float.valueOf(decimalFormat.format(f)); // output is 102.24
//double twoDigitsF = Double.valueOf(decimalFormat.format(f)); also format double value
In answer above it always will return 2 deciaml
examples with String.format("%.02f", f)
2.5555 -> 2.55
2.5 -> 2.50
but do you need to get 2.50 for 2.5?
for avoid to get excessive 0, you can use this solution
val format = DecimalFormat("0.##")
return format.format(floatNum)
Related
Ok I am having an issue trying to put a square root equation in a calculator. I am trying to figure out the expression builder. I know the expression builder takes the math operations of add, subtract, multiply, divide, equals and the parenthesis. What I am doing is trying to build the square root section. I have a simple Percent code to help with the square root.
In the Square root vs the Percent you see I am using binding. So here is the code for both.
On the square root is it possible to use the expression builder? I know there is no absolute formula for square root except for a number that is multipliable with itself like the number 4.
Sqrt(4) = 2
binding.btnSqrt.setOnClickListener {
var square = (tv_equation.text.toString().toDouble() / 2)
binding.tvResult.text = square.toString()
}
So in the event you a non square equation
sqrt(23) = 4.79
How would I simulate that as one function within the button. Can I use expression or would I need to use Kotlin.math
So between the two I divide by 100 on the percent. It works great.
binding.btnPercent.setOnClickListener {
var percentage = (tv_equation.text.toString().toDouble() / 100)
binding.tvResult.text = percentage.toString()
}
All my other buttons work fine and so I am just working on the square root before I can release this to google play.
You would need to use some form of a square root function.
AS you mentioned in your question Kotlin Sqrt Function is a very suitable choice
binding.btnSqrt.setOnClickListener {
if(!tv_equation.text.isNullOrEmpty){
var number = tv_equation.text.toString().toDouble()
binding.tvResult.text = sqrt(number).toString()
}
You can create a sqrt function using the Quake's first inverse square root.
Quake's first inverse square root.
Pseudo Code:
float InvSqrt(float x){
float xhalf = 0.5f * x;
int i = *(int*)&x; // store floating-point bits in integer
i = 0x5f3759df - (i >> 1); // initial guess for Newton's method
x = *(float*)&i; // convert new bits into float
x = x*(1.5f - xhalf*x*x); // One round of Newton's method
return x;
}
So the answer i want to add is a little more suitable with the previous answer. Maybe this will help some people in the future. This solution will also limit the decimal space to 4 decimals.
binding.btnSqrt.setOnClickListener{
val df = DecimalFormat("#.####")
if(!tv_equation.text.isNullOrEmpty())
{
val number = tv_equation.text.toString().toDouble()
binding.tvResult.text = df.format(sqrt(number))
}
}
you can adjust the val df = DecimalFormat("#.####") where the # to as many decimals as you would want.
Why I can not see the double value in a textView?
textView = (TextView) findViewById(R.id.textView);
double x = 5/2;
textView.setText(String.valueOf(x)); // I see this result as 2.0 and not as the 2.5
In Android TextView, you can use in that way,
Use Double.toString:
result = number1/number2
String stringdouble= Double.toString(result);
textview1.setText(stringdouble));
or you can use the NumberFormat:
Double result = number1/number2;
NumberFormat nm = NumberFormat.getNumberInstance();
textview1.setText(nm.format(result));
To force for 3 units precision:
private static DecimalFormat REAL_FORMATTER = new DecimalFormat("0.###");
textview1.setText(REAL_FORMATTER.format(result));
You are seeing 2.0 because 5/2 is integer division. Change the line to double x = 5.0/2; or similar.
See this question for more.
This should work double x = ((double) 5) /2.
I'm doing a math operation beetwen hours, but I've a problem with the float (the java virtual machine approximate is not perfect). So, I decided to convert this operation in BigDecimal...but I've some problems with results..
This is the original code:
public float ConvertTo100(float input)
{
float output = 0.0f;
int hh;
float mm;
hh = (int)input;
mm = input - hh;
output = hh + ((input - hh)/60) * 100;
return output;
}
This is my convertion, but doesn't works:
public float ConvertTo100(float input)
{
BigDecimal inputBD = new BigDecimal(Float.toString(input));
String inpString = String.valueOf(input);
String[] inpsplit = inpString.split("\\.");
BigDecimal hh = new BigDecimal(Float.toString(Integer.parseInt(inpsplit[0])));
BigDecimal output = hh.add((inputBD.subtract(hh).divide(BigDecimal.valueOf(60))).multiply(BigDecimal.valueOf(1000)));
return Float.parseFloat(String.valueOf(output));
}
Where is the problem?? Thank you so much!!! :)
Division by 60 cannot be done exactly in decimal for many inputs. To continue using BigDecimal, you will need to pick a scale and rounding mode for the division. Here's one way of doing it, but read the BigDecimal documentation to see all the options.
BigDecimal output = hh.add((inputBD.subtract(hh).divide(
BigDecimal.valueOf(60), 10, BigDecimal.ROUND_HALF_EVEN))
.multiply(BigDecimal.valueOf(1000)));
However, the main point of using BigDecimal is to get exact representation of decimal fractions. You are not getting that benefit, but are getting the messy code that results from doing arithmetic using method calls instead of infix operators. Unless you need a specific rounding mode, or some finite precision greater than 16.9 significant digits, you would be much better off using double.
private void findLatLongDistance(double prelat,double prelon,double lat,double lon) {
// TODO Auto-generated method stub
try{
double prelatval=prelat;
double prelongval=prelon;
double curlat=lat;
double curlon=lon;
Log.w("inside finalatlon...........................","the daya");
if(prelatval>0.0 && prelongval>0.0 && lat>0.0 && lat>0.0 && gpsdataElements.Speed>0.0){
float distance2 = getDistance(prelatval,prelongval,curlat,curlon);
odometer_sum= (distance2/1000 );
// for maximum value after decimal
//df.setMaximumFractionDigits(0);
//rounding the km digits after decimal
Math.round(distance2);
//for minimum distance after decimal
df.setMinimumFractionDigits(2);
df.format(odometer_sum);
gpsdataElements.Distance = gpsdataElements.Distance + odometer_sum;
}
}catch(Exception e){
e.printStackTrace();
}
}
here is my code. I want distance(i.e km)value digits after decimal is two digits. Example i want km value in 1.54km not like 1.4568923km. How to get like this.I tried a lot for that but i din't got any possible solution. Any one know please help me.
In more simple ways you can do this by using this :
double roundOff = Math.round(yourValue * 100.0) / 100.0;
Otherwise you can also do this as
String.format("%.2f", d)
DecimalFormat formatter = new DecimalFormat(".##");
String s = formatter.format(value);
use this code to format text in two digits after decimal.
double i2=i/60000;
tv.setText(new DecimalFormat("##.##").format(i2));
double roundof = Math.round(a * 100.0) / 100.0;
output:roundoff(eg:12).oo
12.00
Something like this :
String.format("%.2f", distance);
Make function like this pass the value as per you requirment and return value as per your requirment first function will take float value and after decimal it put 3 value as per argument if you want to change decimal value then you can change 3,2,4 etc... Second function will take String value and round it in 3 decimal point:
public static BigDecimal round(float d) {
BigDecimal bd = new BigDecimal(Float.toString(d));
bd = bd.setScale(3, BigDecimal.ROUND_HALF_UP);
return bd;
}
public static BigDecimal round(String d) {
BigDecimal bd = new BigDecimal(Float.parseFloat(d));
bd = bd.setScale(3, BigDecimal.ROUND_HALF_UP);
return bd;
}
I'm trying to create an app that converts celsius to Farhenheit. I want to pass float in .getText() but I'm unable to do so, It is giving me error which say cannot invoke .getText() on the primitive time float. Like I want to take the user input as double and then do the maths calculation. Can you please suggest me the approach to achieve this.
changer = Float.parseFloat(textIn.getText().toString());
textOut.setText(changer);
First you want edittext.gettext().tostring. And String Convert to double.
txtProt = (EditText) findViewById(R.id.Protein);
p = txtProt.getText().toString();
protein = Double.parseDouble(p);
float celsius = Float.parseFloat(textIn.getText().toString());
float farhenheit = (celsius * 1.8f) + 32.0f;
textOut.setText(""+farhenheit);
in the case of converting from farhenheit to celsius:
case(R.id.radioButton2):
float farhenheit = Float.parseFloat(textIn.getText().toString());
float celsius = (( farhenheit - 32.0f ) x 5.0f ) / 9.0f;
textOut.setText(""+celsius);
break;
NB : you should add break; at the end of each case in the switch bloc
i am currently not able to test this but i think this is the answer u need
String text = edittext.gettext.toString()
double f = double.parseDouble(text);
double f2 = do the math to calculate farhenheit
textview.settext(f2.toString())