java - NumberFormat Java 中的格式方法

标签 java text io number-formatting

有人知道 this 的真正用途吗?方法?

format

public StringBuffer format(Object number, StringBuffer toAppendTo, FieldPosition pos)

Formats a number and appends the resulting text to the given string buffer. The number can be of any subclass of Number.

StringBuffer 如何与 FieldPosition 交互(整数/小数)。

简而言之,现实生活中的代码示例将非常有用。

最佳答案

格式化一个 long 值并打印出 long 整数部分的开始和结束索引:

    // Get a default NumberFormat instance.
    NumberFormat numForm = NumberFormat.getInstance();

    // Format some longs using the pattern supplied above.
    StringBuffer dest1 = new StringBuffer(24);
    StringBuffer dest2 = new StringBuffer(24);
    FieldPosition pos = new FieldPosition(NumberFormat.INTEGER_FIELD);

    dest1 = numForm.format(223423L, dest1, pos);
    System.out.println("dest1 = " + dest1);
    System.out.println("INTEGER portion is at: " + pos.getBeginIndex() +
        ", " + pos.getEndIndex());

    dest2 = numForm.format(64000L, dest2, pos);
    System.out.println("dest2 = " + dest2);
    System.out.println("INTEGER portion is at: " + pos.getBeginIndex() +
        ", " + pos.getEndIndex());

输出:

目标1 = 223,423

INTEGER 部分位于:0, 7

目标2 = 64,000

INTEGER 部分位于:0, 6

关于java - NumberFormat Java 中的格式方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18783930/

相关文章:

java - 使用 iText7 形成此布局的最佳方法是什么?

java - 字符串正则表达式解析数据中的分号

c - 在 C 语言中使用方向键

C++写到文件前面

java - 如何使用java从存储在我的计算机上的html文件中提取url?

c - 从 C 中的文件读取和打印时出现奇怪的输出

java - 从 Power BI 获取 accessToken,无需 GUI 身份验证

java - 带有自定义对象的可扩展 ListView

python - 同时读取多个文件的每一行

python - 如何将列表的每个元素保存在 .txt 文件中,每行一个?