Subscribe to Alvin Poh's Blog by RSS reader
Subscribe to Alvin Poh's Blog by Email
Gadgets, Technology, Public speaking and IT from an undergraduate's perspective.
Formatting a Decimal Number to 2 Decimal Places in Java or JSP
I was looking around for the class to format a number to 2 decimal places while I was coding Java, or specifically JSP, and I found it.
First, you need to import the DecimalFormat class, so have this line at the top of your Java file:
import java.text.DecimalFormat;
Or if you’re running JSP:
<%@page import="java.text.DecimalFormat" %>
And here’s the actual code that does the magic:
double price = 10.59;
DecimalFormat priceFormatter = new DecimalFormat("$#0.00");
return priceFormatter.format(price);
That’s all there is to it! Simply change the Formatting string “$#0.00″ to anything you wish. The pound (#) sign simply means there can be optional digits there. The two zero’s (0) to the right of the decimal place means that it has only 2 decimal places, and will be replaced by 0s if you don’t have digits there. Te $ sign right at the start is something that I put in, because I wanted to display my prices in dollars ($).
So for example, you can also have the formatting string as “#0.00 seconds more” and it’ll show “2343.36 seconds more”.
Subscribe to my blog:
RSS reader
Email
Running UNIX commands in your Java application
I was looking around for a method to run commands from the prompt automatically from within my Java application, and then I found it. Here’s the solution - and it works like a charm!
static void doExec1() throws IOException {
// use pipes and I/O redirection
// but without using a shellRuntime runtime = Runtime.getRuntime();
runtime.exec(”ls | wc >out1″);
}
Subscribe to my blog:
RSS reader
Email
Replace/remove character in a String
To replace all occurences of a given character :
String.replaceAll("n", ""); // Remove all n
String.replaceAll("n", "r"); // Replace n by r
To replace a character at a specified position :
public static String replaceCharAt(String s, int pos, char c) {
return s.substring(0,pos) + c + s.substring(pos+1);
}
To remove a character :
public static String removeChar(String s, char c) {
String r = "";
for (int i = 0; i < s.length(); i ++) {
if (s.charAt(i) != c) r += s.charAt(i);
}
return r;
}
To remove a character at a specified position:
public static String removeCharAt(String s, int pos) {
return s.substring(0,pos)+s.substring(pos+1);
}
Subscribe to my blog:
RSS reader
Email
02 Oct 07 | 

