java 在 iReport 中将 Double 格式化为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4832133/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 08:14:40  来源:igfitidea点击:

Formatting Double into a String in iReport

javaformattingjasper-reportsdoubleireport

提问by Gondim

I'm doing a report, that I need to join 4 variables in one. If I treat the variables separately I can format them with no problem. But when I merge them into a String, the double value comes as 0.0 instead of 0.00

我正在做一份报告,我需要将 4 个变量合二为一。如果我单独处理变量,我可以毫无问题地格式化它们。但是当我将它们合并到一个字符串中时,双精度值为 0.0 而不是 0.00

How can I make it comes as the original, 0.00? The code right now looks like this:

我怎样才能使它成为原始的 0.00?现在的代码如下所示:

$F{someDoubleField} + "a string" + $F{anotherDoubleField} + "another string"

It prints:

它打印:

0.0 a string 0.0 another string

instead of:

代替:

0.00 a string 0.00 another string

Remember that iReport uses Java, so maybe, Java code can help me out.

请记住,iReport 使用 Java,所以也许 Java 代码可以帮助我。

回答by Vishal

Use like below:

使用如下:

new DecimalFormat("0.00").format(doubleField) + "str"

回答by Rib47

Do the next:

做下一个:

  1. Open Properties window for your report (right-mouse click on top node in tree view -> Properties)
  2. Set the Languageoption to Java
  3. Use such code in your text field expression:

     String.format("%.2f",$V{Sum}) + " " + $F{unit} 

    Here

    2 - number of digits after dot
    $V{Sum} - Double or Floaf variable (or field - $F{...})

  1. 打开报告的属性窗口(右键单击树视图中的顶部节点 ->属性
  2. 语言选项设置为Java
  3. 在您的文本字段表达式中使用这样的代码:

     String.format("%.2f",$V{Sum}) + " " + $F{unit} 

    这里

    2 - 点后的位数
    $V{Sum} - Double 或 Floaf 变量(或字段 - $F{...})

回答by Gondim

use DecimalFormat

使用十进制格式

here is howto:

这是方法:

double d = 0.00;

NumberFormat nf = new DecimalFormat("0.00");
String format = nf.format(d);

System.out.println(d); //0.00

回答by kburns

Perhaps something like:

也许是这样的:

new DecimalFormat("0.00").format(new java.math.Double(($F{amount} == null) ? 0 : $F{amount}))

new DecimalFormat("0.00").format(new java.math.Double(($F{amount} == null) ? 0 : $F{amount}))