Double Value Aligment Using Local Number Formatter in Java - java

I'm creating an app from java to print sales check:
Locale locale = new Locale("EN", "US");
NumberFormat formatter = NumberFormat.getCurrencyInstance(locale);
final private String contentTicket = "\n"
+ "_________________________________________\n"
+ "TOTAL: " + formatter.format(total) + "\n"
+ "PAY WITH: " + formatter.format(payWith) + "\n"
+ "CHANGE: " + formatter.format(change) + "\n"
+ "_________________________________________\n"
+ " Thank you, have a good day...!!\n"
+ "=========================================\n";
The problem that I have is the alignment when I use the locale formatter for the monetary values.
For example I want the output result be like this:
_________________________________________
TOTAL: $5,000.00
PAY WITH: $10,000.00
CHANGE: $5,000.00
_________________________________________
Thank you, have a good day...!!
=========================================
But, I'm getting this:
_________________________________________
TOTAL: $5,000.00
PAY WITH: $10,000.00
CHANGE: $5,000.00
_________________________________________
Thank you, have a good day...!!
=========================================
The variables total, payWith and change are all Double values.
Thanks in advance...

This seems alright to me as per the right align display,rest strings could be modulated as per requirement. Try this :
public static void main(String[] args) {
double total = 5000;
double payWith = 10000;
double change = 5000;
Locale locale = new Locale("EN", "US");
NumberFormat formatter = NumberFormat.getCurrencyInstance(locale);
System.out.println("-----------------------------------------");
System.out.println("TOTAL:\t\t\t" + formatAlignToRight(formatter.format(total)));
System.out.println("PAY WITH:\t\t" + formatAlignToRight(formatter.format(payWith)));
System.out.println("CHANGE:\t\t\t" + formatAlignToRight(formatter.format(change)));
System.out.println("-----------------------------------------");
System.out.println(" Thank you, have a good day...!!");
System.out.println("=========================================");
}
// To convert a print stream to string from Redirect console output to string in java
public static String formatAlignToRight(String x){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
PrintStream old = System.out;
System.setOut(ps);
System.out.printf("%20s",x); //This is right aligning for 20 characters
System.out.flush();
System.setOut(old);
return baos.toString();
}
Hint : You can't simply use another S.out within one for the
required formatting.

Related

"main" java.util.InputMismatchException [duplicate]

This question already has answers here:
Why am I getting InputMismatchException?
(5 answers)
Closed 6 years ago.
Whenever I try to compile it, it keeps giving me an exception:
This is my source code:
Scanner input = new Scanner(System.in);
DecimalFormat df = new DecimalFormat("#.##");
System.out.print("Gaji Pokok (x 10.000) : ");
double gaji = input.nextDouble();
System.out.print("Lama Tahun Kerja : ");
int th = input.nextInt();
System.out.print("Lama Bulan Kerja : ");
float bl = input.nextFloat();
if ( bl > 12)
{
System.out.println("Inputan bulan anda salah");
System.out.print("Masukkan kembali bulan yang benar : ");
float blnnew = input.nextFloat();
float tukar = blnnew;
bl = tukar;
}
float fak_peng;
fak_peng = Float.valueOf(df.format((th+(bl/12))*2.5));
System.out.print("Jumlah Faktor Penghargaan : " );
System.out.println(fak_peng + " %");
System.out.println("Nilai Sekarang : 1.0000000 " );
float per_mppeg;
per_mppeg = Float.valueOf(df.format(gaji*(fak_peng/100)*1));
System.out.print("Perhitungan MP Pegawai : " );
System.out.println(gaji + " x " + fak_peng + "% x " + " 1.0000000 = Rp." + (per_mppeg) + "(x 10.000)");
System.out.print("MP Perbulan : " );
System.out.println(per_mppeg + " + 100% = Rp." + (per_mppeg) + "(x 10.000)");
System.out.println("MP sekaligus 100% : ");
float peserta;
peserta = Float.valueOf(df.format(100.6650*per_mppeg));
float jd;
jd = Float.valueOf(df.format(14.4820*per_mppeg*0.8));
float anak;
anak = Float.valueOf(df.format(0.6090*per_mppeg*0.8));
float jml;
jml = Float.valueOf(df.format(peserta+jd+anak));
System.out.println(" Peserta = 100.6650 x "+ per_mppeg + " = " + peserta + "(x 10.000)");
System.out.println(" Jd/Dd = 14.4820 x "+ per_mppeg + " x 80% = " + jd + "(x 10.000)" );
System.out.println(" Anak = 0.6090 x "+ per_mppeg + " x 80% = " + anak + "(x 10.000)");
System.out.println("Jumlah Total = "+ jml);
float mpdua;
mpdua = Float.valueOf(df.format (jml*0.2)) ;
float mpdel;
mpdel = Float.valueOf(df.format(per_mppeg*0.8)) ;
System.out.println("MP Sekaligus 20% = "+ mpdua + "(x 10.000)");
System.out.println("MP sekaligus 80% = "+ mpdel + "(x 10.000)");
Your exception is not a compile-time error/exception; it is a runtime exception. It is thrown because the thing the scanner is reading cannot be converted to the type you are asking for (e.g., the next thing the scanner should read is "hello" but you are using scanner.nextInt(), as "hello" cannot be converted to an integer it will raise a InputMismatchException).
In your case the exception is raised when asking for a double. Probably you are using the wrong syntax. You should check which syntax your system uses to represent doubles. On some systems, for example, the fractional and the integer part of a double should be separated with a , and on other systems with a .. So one-half on the first type of system should be written as 0,5 but on the second as 0.5.
In Java the syntax the scanner uses is defined with a Locale instance.
You can check which-one your scanner uses with the locale() method and change it with useLocale() method.
So you should recheck what you give as input.
Besides your problem with the format of double you are creating your DecimalFormat on a discommanded way (see last quote below) and there is another line that may rise an exception ( NumberFormatException ), if you do not pay attention to the Locale instance you are using:
fak_peng = Float.valueOf(df.format((th+(bl/12))*2.5));
As you are using your own format to parse the decimal (new DecimalFormat("#.##");) the string that will be passed to the Float.valueOf method will depend on the Locale instance used to create the DecimalFormat object df (in the code sample you didn't use a specific Locale instance so your systems default Locale instance is used). But Float.valueOf expects its argument to use a specific syntax defined by The Java™ Language Specification regardless to your system as written in the Java API for Float.valueOf:
[...] where Sign, FloatingPointLiteral, HexNumeral, HexDigits, SignedInteger and FloatTypeSuffix are as defined in the lexical structure sections of The Java™ Language Specification, except that underscores are not accepted between digits. If s does not have the form of a FloatValue, then a NumberFormatException is thrown.
(The complete text was too big too include here. Follow this link or the one above to have more info about what Sign, FloatingPointLiteral, HexNumeral, HexDigits, SignedInteger, FloatTypeSuffix and FloatValue exactly represent)
If you want to change the Locale instance used in your DecimalFormat object, read the API for the DecimalFormat class.
To obtain a NumberFormat for a specific locale, including the default locale, call one of NumberFormat's factory methods, such as getInstance(). In general, do not call the DecimalFormat constructors directly, since the NumberFormat factory methods may return subclasses other than DecimalFormat.
In the API (follow link just before quote) they give an example of how you should correctly create an instance of a NumberFormat.
Good luck!

Java - If statement required to display the value as 0.00 instead of 0.0 [duplicate]

This question already has answers here:
Show padding zeros using DecimalFormat
(8 answers)
Closed 7 years ago.
I created this code to display a certain output however the output is displayed with as so:
First Class Parcel - Cost is £3.3
John Smith, 1 Downing Street, SQ13 9DD
Weight = 1.342kg.
This piece of code is the part of the output about(First Class Parcel - Cost is £3.3) However instead of displaying 3.3 I want to display 3.30.
#Override
public String toString() {
String str = "";
double cost = 0.00;
if (this.isFirstClass()){
cost = 3.30;
str = "First Class Parcel";
} else {
cost = 2.80;
str = "Second Class Parcel";
}
return str + " - Cost is £" + cost + "\n" + super.toString() + "\n";
}
This will help you :
DecimalFormat df = new DecimalFormat("#.00");
double d= 23.2;
System.out.println(df.format(d));
Use DecimalFormat. Something on the lines like following
double cost = 3.30;
DecimalFormat df = new DecimalFormat("#.00");
System.out.println("Cost is £" + df.format(cost) );
Have you tried:
String.format( "%.2f", cost);
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#format(java.lang.String,%20java.lang.Object...)

For Loop Depreciation Java [duplicate]

I was wondering if someone can show me how to use the format method for Java Strings.
For instance If I want the width of all my output to be the same
For instance, Suppose I always want my output to be the same
Name = Bob
Age = 27
Occupation = Student
Status = Single
In this example, all the output are neatly formatted under each other; How would I accomplish this with the format method.
System.out.println(String.format("%-20s= %s" , "label", "content" ));
Where %s is a placeholder for you string.
The '-' makes the result left-justified.
20 is the width of the first string
The output looks like this:
label = content
As a reference I recommend Javadoc on formatter syntax
If you want a minimum of 4 characters, for instance,
System.out.println(String.format("%4d", 5));
// Results in " 5", minimum of 4 characters
To answer your updated question you can do
String[] lines = ("Name = Bob\n" +
"Age = 27\n" +
"Occupation = Student\n" +
"Status = Single").split("\n");
for (String line : lines) {
String[] parts = line.split(" = +");
System.out.printf("%-19s %s%n", parts[0] + " =", parts[1]);
}
prints
Name = Bob
Age = 27
Occupation = Student
Status = Single
EDIT: This is an extremely primitive answer but I can't delete it because it was accepted. See the answers below for a better solution though
Why not just generate a whitespace string dynamically to insert into the statement.
So if you want them all to start on the 50th character...
String key = "Name =";
String space = "";
for(int i; i<(50-key.length); i++)
{space = space + " ";}
String value = "Bob\n";
System.out.println(key+space+value);
Put all of that in a loop and initialize/set the "key" and "value" variables before each iteration and you're golden. I would also use the StringBuilder class too which is more efficient.
#Override
public String toString() {
return String.format("%15s /n %15d /n %15s /n %15s", name, age, Occupation, status);
}
For decimal values you can use DecimalFormat
import java.text.*;
public class DecimalFormatDemo {
static public void customFormat(String pattern, double value ) {
DecimalFormat myFormatter = new DecimalFormat(pattern);
String output = myFormatter.format(value);
System.out.println(value + " " + pattern + " " + output);
}
static public void main(String[] args) {
customFormat("###,###.###", 123456.789);
customFormat("###.##", 123456.789);
customFormat("000000.000", 123.78);
customFormat("$###,###.###", 12345.67);
}
}
and output will be:
123456.789 ###,###.### 123,456.789
123456.789 ###.## 123456.79
123.78 000000.000 000123.780
12345.67 $###,###.### $12,345.67
For more details look here:
http://docs.oracle.com/javase/tutorial/java/data/numberformat.html

NumberFormatException occurs with different regional settings

I'm developing an application in Java and found this strange behaviour:
if the regional settings format is set to Hungarian (system default) via the Control Panel, I get this exception, but if I set it to an English one, it works perfectly. Also works on a virtual Mandriva where I'm developing the program in the first place.
This is the code snippet that causes the problem:
public String stattxt(){
double dt = time_avg();
double bpm = (Double.compare(dt, 0) == 0) ? 0 : msec2bpm(dt);
String s = "<html>Number of control points: " + timestamps.size() + "<br>Average dt: " +
Double.valueOf(new DecimalFormat("#.####").format(dt).toString()) + " ms<br>" +
"Average BPM: " + Double.valueOf(new DecimalFormat("#.####").format(bpm).toString()) + "<br>&nbsp</html>";
return s;
}
where both time_avg() and msec2bpm return double (not Double by any chance) values.
How could I make this work regardless to regional settings? Any help would be appreciated.
It seems like you're using
Double.valueOf(new DecimalFormat("#.####").format(dt).toString())
to round a number to 4 decimal places, but this looks like a hack to me and will fail due to regionalization settings (Hungary probably uses a decimal comma, not a decimal point.)
So, instead round doubles using something like:
rounded = Math.round(original * 10000)/10000.0;
And, if you want to create a string which is a double rounded to 4 decimal places, use String.format()
String.format("%.4f", original);
It looks like you should just skip the Double.valueOf:
public String stattxt(){
double dt = time_avg();
double bpm = (Double.compare(dt, 0) == 0) ? 0 : msec2bpm(dt);
String s = "<html>Number of control points: " + timestamps.size() + "<br>Average dt: " +
new DecimalFormat("#.####").format(dt) + " ms<br>" +
"Average BPM: " + new DecimalFormat("#.####").format(bpm) + "<br>&nbsp</html>";
return s;
}
Why are you converting String to Double and then again to String? Do it like this:
public String stattxt(){
double dt=time_avg();
double bpm=(Double.compare(dt, 0)==0)?0:msec2bpm(dt);
String s="<html>Number of control points: "+timestamps.size()+"<br>Average dt: "+
new DecimalFormat("#.####").format(dt).toString()+" ms<br>"+
"Average BPM: "+Double.valueOf(new DecimalFormat("#.####").format(bpm).toString())+"<br>&nbsp</html>";
return s;
}

Java output formatting for Strings

I was wondering if someone can show me how to use the format method for Java Strings.
For instance If I want the width of all my output to be the same
For instance, Suppose I always want my output to be the same
Name = Bob
Age = 27
Occupation = Student
Status = Single
In this example, all the output are neatly formatted under each other; How would I accomplish this with the format method.
System.out.println(String.format("%-20s= %s" , "label", "content" ));
Where %s is a placeholder for you string.
The '-' makes the result left-justified.
20 is the width of the first string
The output looks like this:
label = content
As a reference I recommend Javadoc on formatter syntax
If you want a minimum of 4 characters, for instance,
System.out.println(String.format("%4d", 5));
// Results in " 5", minimum of 4 characters
To answer your updated question you can do
String[] lines = ("Name = Bob\n" +
"Age = 27\n" +
"Occupation = Student\n" +
"Status = Single").split("\n");
for (String line : lines) {
String[] parts = line.split(" = +");
System.out.printf("%-19s %s%n", parts[0] + " =", parts[1]);
}
prints
Name = Bob
Age = 27
Occupation = Student
Status = Single
EDIT: This is an extremely primitive answer but I can't delete it because it was accepted. See the answers below for a better solution though
Why not just generate a whitespace string dynamically to insert into the statement.
So if you want them all to start on the 50th character...
String key = "Name =";
String space = "";
for(int i; i<(50-key.length); i++)
{space = space + " ";}
String value = "Bob\n";
System.out.println(key+space+value);
Put all of that in a loop and initialize/set the "key" and "value" variables before each iteration and you're golden. I would also use the StringBuilder class too which is more efficient.
#Override
public String toString() {
return String.format("%15s /n %15d /n %15s /n %15s", name, age, Occupation, status);
}
For decimal values you can use DecimalFormat
import java.text.*;
public class DecimalFormatDemo {
static public void customFormat(String pattern, double value ) {
DecimalFormat myFormatter = new DecimalFormat(pattern);
String output = myFormatter.format(value);
System.out.println(value + " " + pattern + " " + output);
}
static public void main(String[] args) {
customFormat("###,###.###", 123456.789);
customFormat("###.##", 123456.789);
customFormat("000000.000", 123.78);
customFormat("$###,###.###", 12345.67);
}
}
and output will be:
123456.789 ###,###.### 123,456.789
123456.789 ###.## 123456.79
123.78 000000.000 000123.780
12345.67 $###,###.### $12,345.67
For more details look here:
http://docs.oracle.com/javase/tutorial/java/data/numberformat.html

Categories

Resources