Tag: 字符串格式化

Java printff字符串只输出格式

如何使用printf格式化输出。 假设我想在格式化程序中打印以下内容。 testing testing testing testing testingggg testingggg testingggg testingggg 我不问有关使用“\ t”,我问的是printf样式格式? 如果有人可以给我建议和例子。 或者可以与示例链接。 我可以做到符合我的需要。

如何使用bean中的属性格式化字符串

我想使用格式创建一个String,用bean中的属性替换格式的一些标记。 是否有支持此function的库或者我是否必须创建自己的实现? 让我举一个例子来certificate。 说我有一个豆Person ; public class Person { private String id; private String name; private String age; //getters and setters } 我希望能够指定类似的格式字符串; “{name} is {age} years old.” “Person id {id} is called {name}.” 并使用bean中的值自动填充格式占位符,例如; String format = “{name} is {age} old.” Person p = new Person(1, “Fred”, “32 years”); String formatted = doFormat(format, person); […]

NumberFormat文本字段,不带逗号

我有一个JFormattedTextField ,我想接受5位数的数字。 以下代码正常工作: myNumberBox = new JFormattedTextField(NumberFormat.getIntegerInstance()); 但是,当我在字段中键入“12345”并切换焦点时,由于我的语言环境而插入逗号,使文本“12,345”。 如何防止将逗号添加到我的输入中? 更好的是,即使用户插入逗号,它们也可以被删除吗?

DecimalFormat.format()的更快替代方案?

为了提高性能,我使用VisualVM采样器分析了我的一个应用程序,使用的最小采样周期为20ms。 根据分析器,主线程在DecimalFormat.format()方法中花费了近四分之一的CPU时间。 我使用带有0.000000模式的DecimalFormat.format()将double数字“转换”为具有正好六位小数的字符串表示。 我知道这种方法相对昂贵并且被称为很多次,但我仍然对这些结果感到有些惊讶。 这种采样分析仪的结果在多大程度上准确? 我将如何validation它们 – 最好不要求助于仪器分析仪? 对于我的用例,是否有更快的替代DecimalFormat ? 推出自己的NumberFormat子类是否有意义? 更新: 我创建了一个微基准来比较以下三种方法的性能: DecimalFormat.format() :单个DecimalFormat对象重复使用多次。 String.format() :多个独立调用。 在内部,这种方法归结为 public static String format(String format, Object … args) { return new Formatter().format(format, args).toString(); } 因此我期望它的性能与Formatter.format()非常相似。 Formatter.format() :单个Formatter对象重复使用多次。 此方法稍微不方便 – 使用默认构造函数创建的Formatter对象将format()方法创建的所有字符串追加到内部StringBuilder对象,该对象无法正确访问,因此无法清除。 因此,对format()多次调用将创建所有结果字符串的串联 。 为了解决这个问题,我提供了自己的StringBuilder实例,我在使用之前通过setLength(0)调用清除了该实例。 结果有趣: DecimalFormat.format()是每次调用1.4us的基线。 String.format()在每次调用2.7us时减慢了两倍。 Formatter.format()在每次调用2.5us时也慢了两倍。 现在看来, DecimalFormat.format()仍然是这些替代品中最快的。

格式化BigDecimal,无需科学记数法,具有完全精确度

我想将BigDecimal转换为String以进行打印,但打印出所有数字而没有科学记数法。 例如: BigDecimal d = BigDecimal.valueOf(12334535345456700.12345634534534578901); String out = d.toString(); // Or perform any formatting that needs to be done System.out.println(out); 我想打印12334535345456700.12345634534534578901 。 现在我得到: 1.23345353454567E+16 。

Java – 使用格式化程序标志从左侧截断字符串

我有一个字符串,说: String s = “0123456789”; 我想用格式化程序填充它。 我可以这两种方式: String.format(“[%1$15s]”, s); //returns [ 0123456789] 要么 String.format(“[%1$-15s]”, s); // returns [0123456789 ] 如果我想截断我做的文字 String.format(“[%1$.5s]”, s); // returns [01234] 如果我想从左边截断,我想我可以这样做: String.format(“[%1$-.5s]”, s); // throws MissingFormatWidthException 但这失败了,所以我尝试了这个: String.format(“[%1$-0.5s]”, s); // throws MissingFormatWidthException 以及: String.format(“[%1$.-5s]”, s); // throws UnknownFormatConversionException 那么我如何使用格式标志从左侧截断?

右边用零填充

对不起,如果这个问题已经提出,我已经深入搜索,没有任何内容。 现在,我知道: String.format(“%05d”, price); 将左边的零填充我的价格,因此25的价格将导致00025 如果我想将它们填充到右边怎么办,结果是25000 ? 如何仅使用String.format模式执行此操作?