java - Int String 格式问题

标签 java string formatting int

我正在返回这个,它类似于你如何看待美元,$“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/

相关文章:

c# - 筛选列表数据 C#

python - string.split 错误? Python

css - 样式文本框文本

python - Nosetests 断言错误输出格式

java - 如何使用 selenium 对点击时触发的事件进行自动化分析测试?

java - Spring MVC 不明确的映射。无法映射

java - swing 中单选按钮上的 MouseListener

c# - 在 C# 中安全地解析 XML

r - 在 R 中绘制 2D 表格对象时控制轴标签的格式/位置

java - 为什么 Maven + Spring Boot 会创建巨大的 jar 文件?