Where would I insert this in my code? I have a inputs and a message box that I need to get to two decimals but I can't figure out where I should put it.
-
what language you are using? – Anonymous Duck Sep 03 '15 at 05:30
-
1possible duplicate of [c# - How do I round a decimal value to 2 decimal places (for output on a page)](http://stackoverflow.com/questions/164926/c-sharp-how-do-i-round-a-decimal-value-to-2-decimal-places-for-output-on-a-pa) – Ruchi Sep 03 '15 at 05:32
1 Answers
If you don’t want to print out the String and just want to format it for later use, you can use the static format method of the String class. It works in exactly the same way as printf as far as formatting is concerned, but it doesn’t print the String, it returns a new formatted String.
String.format "%[argument number] [flags] [width] [.precision] type"
"%" is a special character in formatted String and it denotes start of formatting instruction. String.format() can support multiple formatting instruction with multiple occurrence of "%" character in formatting instruction.
"argument number" is used to specify correct argument in case multiple arguments are available for formatting.
"flags" is another special formatting instruction which is used to print String in some specific format for example you can use flag as "," to print comma on output.
"width" formatting option denotes minimum number or character will be used in output but in case if number is larger than width then full number will be displayed but if its smaller in length then it will be be padded with zero.
"precision" is using for print floating point formatted String, by using precision you can specify till how many decimal a floating point number will be displayed in formatted String.
"type" is the only mandatory formatting option and must always comes last in format String also input String which needs to be formatted must be with same type specified in "type" parameter.
public class StringFromatExample {
public static void main(String[] args) { String s1 = String.format("%-4.5f %.20f", 35.23429837482,5.2345678901); System.out.println(s1); }
}
the output will be
35.23430 5.23456789010000000000

- 1
- 3