【问题标题】:Android Java Decimal Format - Zero is hidden after decimal pointAndroid Java Decimal Format - Zero is hidden after decimal point
【发布时间】:2023-01-06 21:30:49
【问题描述】:

In my app, i want to be able to format numbers to string (with commas) in a TextView e.g 123456.000 to 123,456.000. But the problem is when i type zero (0) as the last number after the decimal point, it shows nothing until i type another number. For example, if i type 123456.000, i get 123,456. The zeros doesn't show until i type another number like "1" then i get 123,456.0001. Please how do i make zeros show as last number after decimal point? Below are some sample codes.

I apologise for the clumsiness of the code. I manually typed it with my phone.

TextView txtView;
boolean NumberClicked = false;
String number = "";

// format pattern
DecimalFormat formatter = new DecimalFormat("#,###.#########");


// input dot (decimal point)
dot.setOnClickListener (new View.OnClickLstener() {
public void onClick(View view) {
if    (!txtView.getText.toString.contains(".") {
input(".");}}});

// input zero (0)
zero.setOnClickListener (new View.OnClickLstener() {
public void onClick(View view) {
input("0");
}});

// input one (1)
one.setOnClickListener (new 
View.OnClickLstener() {
public void onClick(View view) {
input("1");}});

// input method
public void input (String view) {
if (!numberClicked) {
number = view;
numberClicked = true;
} else {
number = number + view;
}
// print the entered numbers to
//the TextView after formatting 
if (!number.endsWith(".")) { txtView.setText(formatter.format(Double.parseDouble(number)));}}

enter code here

【问题讨论】:

标签: java android zero decimalformat decimal-point


【解决方案1】:

You may try this code sn-p:

DecimalFormat df = new DecimalFormat("#,##0.0#");
df.setMinimumFractionDigits(3);
String value = df.format(123456.000);

Output: 123,456.000

For more info pls click here.

【讨论】:

    【解决方案2】:

    Try with:

    String.format("%,.03f", 123456.000)
    

    【讨论】:

      猜你喜欢
      • 2013-01-27
      • 1970-01-01
      • 2020-12-04
      • 1970-01-01
      • 1970-01-01
      • 2015-02-04
      • 1970-01-01
      • 2018-07-25
      • 2016-05-15
      相关资源
      最近更新 更多