在J中的小数点后格式化两位数字到两位数字
问题描述:
如何将中的double
值格式化为小数点后两位数字(不进行算术运算)?在J中的小数点后格式化两位数字到两位数字
double x = 3.333333;
String s = String.Format("\rWork done: {0}%", new Double(x));
System.out.print(s);
我以为J#
是几乎相同Java
,但下面Java
代码提供J#
一个不同的结果:
double x = 3.333333;
String s = String.format("\rWork done %1$.2f%%", x);
System.out.print(s);
(由于J#
接近死了的和不支持,我用Visual J# 2005
)
答
String.format()
API是在Java中引入的1.5,所以re没有机会可以使用它Visual J ++或Visual J#。
有两种方法可以解决您的问题。
-
使用Java 1.1 API(与任何的Java,J ++和J#作品):
import java.text.MessageFormat; /* ... */ final double d = 3.333333d; System.out.println(MessageFormat.format("{0,number,#.##}", new Object[] {new Double(d)})); System.out.println(MessageFormat.format("{0,number,0.00}", new Object[] {new Double(d)}));
注意的是,尽管这两种格式对于给定的双A合作,
0.00
和#.##
之间有区别。 -
使用.NET API。这里的C#代码片段已经做了你需要的东西:
using System; /* ... */ const double d = 3.333333d; Console.WriteLine(String.Format("{0:F2}", d)); Console.WriteLine(String.Format("{0:0.00}", d)); Console.WriteLine(String.Format("{0:0.##}", d));
现在,同样的代码翻译成J#:
import System.Console; /* ... */ final double d = 3.333333d; Console.WriteLine(String.Format("Work done {0:F2}%", (System.Double) d)); Console.WriteLine(String.Format("{0:Work done 0.00}%", (System.Double) d)); Console.WriteLine(String.Format("{0:Work done #.##}%", (System.Double) d));
请注意,您需要将
double
参数转换为System.Double
, 不是java.lang.Double
,为了格式化工作(见http://www.functionx.com/jsharp/Lesson04.htm)。
也许'的String =的String.Format( “\ rWork完成:{0:D2}%”,X));'如C# –
@Bob_我将试试看。不知道这也适用于'C#'。我主要使用'String s = String.format(“\ rWork done {0:0.00}%”,x)'; – Matthias
@Bob__不起作用。 – Matthias