如何使用Java DecimalFormat强制小数点?

问题描述

我有两个双打代码:

double a = 2000.01;
double b = 2000.00;
String pattern = "0.##";
DecimalFormat dc = new DecimalFormat(pattern); // <- "0.##" does not work
System.out.println(dc.format(a));
System.out.println(dc.format(b));

需要一种会产生以下输出的模式:

2000.01
2000.

b 存在小数点,即使未打印零也是如此

解决方法

一种选择是使用'DecimalFormat.setDecimalSeparatorAlwaysShown'始终包含小数。

示例:

double a = 2000.01;
double b = 2000.00;
String pattern = "0.##";
DecimalFormat df = new DecimalFormat(pattern);
df.setDecimalSeparatorAlwaysShown(true);
System.out.println(df.format(a));
System.out.println(df.format(b));

样本输出:

2000.01
2000.
,

使用此模式:def process_view(request,view_func,view_args,view_kwargs): """ do something """ def simple_middleware(get_response): # One-time configuration and initialization. def middleware(request): # Code to be executed for each request before # the view (and later middleware) are called. response = get_response(request) # Code to be executed for each request/response after # the view is called. return response middleware.process_view = process_view return middleware

它应该像这样:

#0.00

哪些印刷品:

double a = 2000.01;
double b = 2000.00;
String pattern = "#0.00";
DecimalFormat dc = new DecimalFormat(pattern);
System.out.println(dc.format(a));
System.out.println(dc.format(b));
,

扩展DecimalFormat

public class MDF extends DecimalFormat {
  public String format(double d) {
    String s = super.format(d);
    if (!s.contains(".")) {
      return s + ".";
    }
    return s;
  }
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...