在J#

时间:2016-08-23 20:04:58

标签: 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

1 个答案:

答案 0 :(得分:1)

String.format() API是在Java 1.5 中引入的,因此您无法在 Visual J ++ Visual J#中使用它

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

  1. 使用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)}));
    

    请注意,尽管两种格式都适用于给定的双倍,但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 )。