簡體   English   中英

使用string.format,雙精度轉換為字符串

[英]Using string.format with doubles converted to string

所以我在這里有些不知所措。 我試圖將我的字符串格式化為只有2位小數。 我知道你在想什么,我必須把它們作為字符串才能將它們附加到我的JTextArea(這些是我的arrayList的一小部分)。 所以我使用String.valueof()將雙精度轉換為字符串,這很好,但是我需要格式化它們才能打印出帶有2位小數的字符串。 我的演習等如下

class inventoryItem { //Delcare variables below

String itemName;
String newUnit;
String newFee;
String newValue;
String newInventoryValue;
int itemNumber;
int inStock;
double unitPrice;
double value;
double restockingFee;

double inventoryValue;

public inventoryItem(String itemName, int itemNumber, int inStock, double unitPrice) { //declare variables for this class
    this.itemName = itemName;
    this.itemNumber = itemNumber;
    this.inStock = inStock;
    this.unitPrice = unitPrice;
    restockingFee = .05 * value;
    stockValue();

}

public void stockValue() {
    value = unitPrice * inStock;
    restockingFee = .05 * unitPrice;
    inventoryValue = restockingFee + value;
    newUnit = String.valueOf((double) unitPrice);
    newFee = String.valueOf((double) restockingFee);
    newValue = String.valueOf((double) value);
    newInventoryValue = String.valueOf(inventoryValue);

我試過做類似的事情

outputText.append("something = $" + (String.format("%.2f, newUnit))

但這似乎不起作用。 有沒有辦法在使用String.valueOf時可以做到這一點?

使用DecimalFormat

樣品:

double unitPrice = 1.23235;
java.text.DecimalFormat decimalFormat = new java.text.DecimalFormat( "#,###,###,##0.##" );
String formattedUnitPrice = decimalFormat.format(unitPrice);

產量將為1.23

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM