Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/jsf/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java-使用Object和toString方法格式化字符串以显示一个磅符号和一个带两个前导零的十进制数?_Java_Formatting - Fatal编程技术网

Java-使用Object和toString方法格式化字符串以显示一个磅符号和一个带两个前导零的十进制数?

Java-使用Object和toString方法格式化字符串以显示一个磅符号和一个带两个前导零的十进制数?,java,formatting,Java,Formatting,我试过了 System.out.println(myLorry.toString(registration, myCar.calcCharge())); 哪个输出 Registration: TA17 NDD Charge: 7.0 我想让我的程序输出 Registration: TA17 NDD Charge: £7.00 如何正确设置格式 编辑: 为什么格式不正确?它说它需要两个参数,但只能找到一个。我需要使用toString方法调用对象 System.out.printf("%s £

我试过了

System.out.println(myLorry.toString(registration, myCar.calcCharge()));
哪个输出

Registration: TA17 NDD Charge: 7.0
我想让我的程序输出

Registration: TA17 NDD Charge: £7.00
如何正确设置格式

编辑: 为什么格式不正确?它说它需要两个参数,但只能找到一个。我需要使用toString方法调用对象

System.out.printf("%s £%.2f" ,myCar.toString(registration, myCar.calcCharge()));

如@davidxxx,建议您在评论中使用

DecimalFormat d = new DecimalFormat("'£'0.00");
System.out.println(d.format(7.0));
输出

£7,00

如果您对
点(.)
逗号(,)
有问题,则可以使用
十进制符号

DecimalFormat d = new DecimalFormat("'£'0.00");
DecimalFormatSymbols sym = DecimalFormatSymbols.getInstance();
sym.setDecimalSeparator('.');
d.setDecimalFormatSymbols(sym);

一个解决方案是使用。 e、 g

输出:

£7.00

事实上,你应该考虑两件事:

  • 使用浮动零件的固定位数格式化数值

  • 设置小数分隔符字符

第二点可能很重要,因为根据JVM设置的区域设置,您可以得到一个不同的结果:
7.00
7,00

因此,您可以在
DecimalFormat
中指定
“.0.00”
模式,并使用特定的
DecimalFormatSymbols
创建
DecimalFormat
实例,以确保将
字符用作十进制符号

您可以这样做,例如:

float f = 7;
DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols();
otherSymbols.setDecimalSeparator('.');
NumberFormat formatter = new DecimalFormat("£0.00", otherSymbols);
String valueFormated = formatter.format(f);
但事实上,更简单的方法是使用
String.format()
方法,方法是指定预期的模式(浮动部分为两位数字)和使用
作为十进制分隔符的
区域设置

float f = 7;
String valueFormated = String.format(Locale.US, "£%.2f", f);

解决了!我完全看错了我的程序,以下是我的解决方案:

  String toString(String rn, double calcCharge)
        {
            DecimalFormat d = new DecimalFormat("£0.00");
            return "Registration: " + rn + " Charge: " + d.format(calcCharge());
        }

我必须修改我的子类继承自的类

您可以使用
DecimalFormat
十进制格式是如何工作的?您读过它的文档了吗?如果您搜索“Java DecimalFormat”,它们是免费提供的。您可能希望重写myLorry类中的toString方法。您可以根据需要格式化字符串it@Nebula我刚刚做了一个回答。为什么这个不正确?System.out.printf(“%s.%.2f”myCar.toString(registration,myCar.calcCharge());您使用了两个格式占位符(%s%f),但仅使用了一个参数(字符串)
  String toString(String rn, double calcCharge)
        {
            DecimalFormat d = new DecimalFormat("£0.00");
            return "Registration: " + rn + " Charge: " + d.format(calcCharge());
        }