2017-02-20 24 views
-2

我有雙精度型變量,我需要使它成爲0.00格式。正常工作與此:在java中有兩個十進制數字的雙精度(沒有java.text.DecimalFomat)

sum = Math.round(sum*100.00)/100.00; 

我通過

return Double.toString(sum); 

歸還但是,相反的,例如2.40它給了我2.4(末尾丟失0)。

我有這方面的進口可用:

import static org.junit.Assert.*; import java.util.*;import org.junit.Test; 

我解決了的DecimalFormat和BigDecimal的問題,但我不能使用這些庫。

+0

爲什麼不用'DecimalFormat'? NB這些不是'十進制數字',它們是具有實際值的浮點變量。 – EJP

+0

沒有DecimalFormat,因爲它只適用於應用程序,我只能寫一部分代碼。感謝提供十進制數字的提示,我已經學習了除英語以外的其他語言的數學,所以有時候很難處理術語。 – Wojtek

回答

3

你可以簡單format字符串

double num = 2.402; 
String output = String.format("%.2f", num); 
System.out.println(output); 
+0

只是慢一點,你的觀點:-) – thst

0

您可以使用java.lang.String#format()java.util.Formatter打印便利地數量。

return String.format("%.2f", sum); 

應該做的工作。

0

只需使用格式 例如:

package com.test; 

import java.lang.*; 
import java.util.*; 

public class StringDemo { 

    public static void main(String[] args) { 

    double piVal = Math.PI; 

    /* returns a formatted string using the specified format 
    string, and arguments */ 
    System.out.format("%f\n", piVal); 
    } 
    } 
output: 3.141593 

的%F允許的數字的量你想incudes OT%.2f包含後2位數字。 enter image description here

相關問題