在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

+0

也许'的String =的String.Format( “\ rWork完成:{0:D2}%”,X));'如C# –

+0

@Bob_我将试试看。不知道这也适用于'C#'。我主要使用'String s = String.format(“\ rWork done {0:0.00}%”,x)'; – Matthias

+0

@Bob__不起作用。 – Matthias

String.format() API是在Java中引入的1.5,所以re没有机会可以使用它Visual J ++Visual J#

有两种方法可以解决您的问题。

  1. 使用Java 1.1 API(与任何的JavaJ ++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#.##之间有区别。

  2. 使用.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)。