在 J# 中将小数点后的双精度格式化为 2 位数字
Formatting double to 2 digits after decimal point in J#
如何将 J#
中的 double
值格式化为小数点后两位(不进行算术运算)?
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 中引入的,所以你不可能在 Visual 中使用它J++ 或 Visual J#.
有 2 种方法可以解决您的问题。
使用 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
和 #.##
之间存在差异。
使用.NETAPI。这是执行您需要的 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).
如何将 J#
中的 double
值格式化为小数点后两位(不进行算术运算)?
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 中引入的,所以你不可能在 Visual 中使用它J++ 或 Visual J#.
有 2 种方法可以解决您的问题。
使用 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
和#.##
之间存在差异。使用.NETAPI。这是执行您需要的 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).