C/C++と同じ感じでできるっぽい。
ただそれをやろうとすると、String.format
で再度メッセージを囲ってあげないといけない。
System.out.println(String.format("ceil: %.2f", result_2));
参考:
You can use these Format Specifiers for different data types
%c or %C Display characters %d Displays a decimal (base 10 ) integer %e or %E Display a floating point number in exponential notation %f Display a floating point value in decimal format %s or %S Display Strings %b or %B Display boolean values %g (%G) float or double use %f or %e as required %o int unsigned octal value %p pointer address stored in pointer %s array of char sequence of characters or String %u int unsigned decimal %x (%X) int unsigned hex value %% Display a % sign You can use whitespace characters which are space ( ' ' ) tab ( '\t' ) carriage return ( '\r' ) newline ( '\n' ) ormfeed ( '\f' )
2/21 追記
下記のようなコードをやると出力結果が、あれ?ってなることがある。
こんなときこそString.format
を使用する。
public class Main { public static void main(String[] args) { for (int i=2; i<9; i++) { System.out.println(calculateInterest(10000, i)); //System.out.println(String.format("%.2f",calculateInterest(10000, i))); // -> これ使う } } public static double calculateInterest(double amount, double interestRate) { return (amount * (interestRate/100)); } }
結果
200.0 300.0 400.0 500.0 600.0 700.0000000000001 800.0