When I do an account to get the % of a number, I have a problem, let me explain:
I take 5% of 7.74 and it is 0.3870 but I want it to only show me two numbers in the decimal part, that is 0.38 . How can I do this?
And another question I have, is it possible that the result is with a , and not a . ?
This is how I do the process:
public class MainActivity extends AppCompatActivity {
EditText uno;
TextView tres;
Button btn1;
static final BigDecimal PORCENTAJE_CINCO = new BigDecimal("0.05");
public BigDecimal calculaCincoPorCiento(BigDecimal numero) {
return numero.multiply(PORCENTAJE_CINCO);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uno = (EditText) findViewById(R.id.uno);
tres = (TextView) findViewById(R.id.tres);
btn1 = (Button) findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
BigDecimal aux0 = new BigDecimal(uno.getText().toString());
BigDecimal aux1 = calculaCincoPorCiento(aux0);
tres.setText(aux1 + " " + "es el 5%");
}
});
}
}
Thank you!
You can use
setScale
to show the number of decimals you want, and also, you can put if you want it to be rounded half up or half down. Here's an example of rounding up to two decimal places:To display it with a
,
instead of a.
you can convert it toString
and then replace the.
with a,
: