我正在返回这个,它类似于你如何看待美元,$“32.95”等。我以美分计算它,它是一个整数,但问题是后半部分会切断 10 美分部分,如果数量小于该数量。例如,如果我有“32.08”,它将返回“32.8”。有任何想法吗 ?我知道我需要一个 if,但我不知道如何写它。
public String toString()
{
return (cents / 100)+ "." + (cents % 100);
}
最佳答案
您可以使用http://java.sun.com/j2se/1.5.0/docs/api/java/text/DecimalFormat.html
DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers. It has a variety of features designed to make it possible to parse and format numbers in any locale, including support for Western, Arabic, and Indic digits. It also supports different kinds of numbers, including integers (123), fixed-point numbers (123.4), scientific notation (1.23E4), percentages (12%), and currency amounts ($123). All of these can be localized.
String pattern = "$###,###.###";
double value = 12345.67;
DecimalFormat myFormatter = new DecimalFormat(pattern);
String output = myFormatter.format(value);
System.out.println(value + " " + pattern + " " + output);
// => 12345.67 $###,###.### $12,345.67
关于java - Int String 格式问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1898343/