dont quite understand string.format, and the java documentation - java

i couldnt find anything specific for this, so i was wondering how do i use string format to make a double value output in exactly this format $XXXX.XX, could anyone show me how this is done, and break each piece of the method down of what it is actually doing because i just dont know how to apply what i see on the docs im using to what im trying to output in the method and i would much rather understand what each 'command/argument' means or does so that I dont have to ask a question like this.
https://www.javatpoint.com/java-string-format // the docs im using
the code im trying to format,
value taken from explicit
double dollarAmt = String.format(????);

so i was wondering how do i use string format to make a double value
output in exactly this format $XXXX.XX
There are a lot of ways to do that. Here is one:
import java.text.DecimalFormat;
import java.text.NumberFormat;
...
double someNumber = 21.12;
NumberFormat formatter = new DecimalFormat("$0000.00");
String result = formatter.format(someNumber);

Related

Adding a leading zero to a large string in Java

I am currently making an auction program in Java, I am trying to work out deadlines, however my date keeps coming out as (7/04/2013 11:22), is there a way to use String.format to add a leading zero to this date when it is a one digit day?
String timeOne = Server.getDateTime(itemArray.get(1).time).toString()
It causes me a problem later on when I try to sub string it, and it is less than 17 characters long.
Thanks in advance, James.
#Leonard Brünings answer is the right way. And here's why your original code is the wrong way ... even if it worked.
The javadoc for Calendar.toString() says this:
"Return a string representation of this calendar. This method is intended to be used only for debugging purposes, and the format of the returned string may vary between implementations."
Basically you are using toString() for a purpose that the javadoc says you shouldn't. Even if you tweaked the output from toString(), the chances are that your code would be fragile. A change in JVM could break it. A change of locale could break it.
Simply use the SimpleDateFormat
import java.text.SimpleDateFormat;
Calendar timeOne = Server.getDateTime(itemArray.get(1).time)
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm")
System.out.println(sdf.format(timeOne.getTime()))

Formatting string in Java

Hi I'm new to java so this is going to seem a bit tame. Anyway, in objC, when I want to insert a variable into a string, I would do it like this:
NSString *string = [NSString stringWithFormat:#"test%i", variable];
How do I do this in java?
There are number of ways, but the java.lang.String.format() method is an easy one:
String message = String.format("There are %d ways to leave your lover", 50);
Using the String.format() method. Take a look at the documentation for understanding all the different formatting options available.

How do I effectively use the Modulus Operator in Java

I am doing a college assignment in Java that deals with currency. For that I am advised to use ints instead of doubles and then later convert it to a dollar value when I print out the statement.
Everything works fine until I do calculations on the number 4005 (as in $40.05 represented as an int). I am pasting the part of code I am having problems with, I would appreciate if someone could tell me what I am doing wrong.
import java.io.*;
class modumess {
public static void main(String[] args) {
int money = 4005; //Amount in cents, so $40.05;
// Represent as normal currency
System.out.printf("$%d.%d", money/100, money%100);
}
}
The above code, when run, shows $40.5, instead of $40.05. What gives?
Kindly note that this is for my homework and I want to learn, so I would really appreciate an explanation about the root of the problem here rather than just a simple solution.
EDIT: Following Finbarr's answer, I have added the following to the code which seems to have fixed the problem:
if (money%100 < 10) {
format = "$%d.0%d";
}
Is this a good way to do it or am I over-complicating things here?
EDIT: I just want to make it clear that it was both Finbarr and Wes's answer that helped me, I accepted Wes's answer because it made it clearer for me on how to proceed.
A better way would be something like this for a general case:
format = "%d.%02d";
%02d gives you 0 padding for 2 digits. That way you don't need the extra if statement.
See this for more explanation of things you can do in format: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax
The modulus operator returns the remainder after division without fractional calculation. In this case, 4005%100 returns 5 as the remainder of 4005/100 is 5.

Standard deviation of input numbers with JAVA

I am new to this place and in need of serious help. After spending 6 hours trying to figure out this, I am going insane and need help. Here is the question i am assigned.
Create the StandardDeviation project. Write a java program that reads a set of double data values. When all the values have been read, print out the count of the values, the average and the standard deviation.
I cannot find any commands that allow for a group of entered numbers at once and be read by JAVA. Could someone please help me get started or point to somewhere where i can find relative problems or examples. Thank you very much. All i know is that it supposed to start with
while (in.hasNextDouble())
I'm assuming this is homework.
You're going to want to look at java.util.Scanner, it will let you do while( Scanner.hasNextDouble() ) which you can then sum. You're also going to want to keep track of all the numbers so you should take a look at java.util.ArrayList.
Note: to use ArrayList properly you'll have to use the Double class, which can be treated almost exactly like a double primitive, or you can use arrays instead of ArrayList.
Take a look at the Scanner class. It can read input data and you can repeatedly call hasNextDouble and nextDouble on it to pull out the data.
From javaman (http://www.daniweb.com/members/javaman2/471995) I find a solution. It looks like the Scanner class provides capabilities in this area also.

Java DecimalFormat problem

I would like to format numbers of type double with a German locale in Java. However something goes wrong since the output of the following code is : 0.0
package main;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
public class Test {
private static String decimal2Format = "000.000";
public static void main(String args[]){
DecimalFormat format = (DecimalFormat)NumberFormat.getInstance(new Locale("de"));
double value = 0;
try {
format.applyPattern(decimal2Format);
value = format.parse("0.459").doubleValue();
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(value);
}
}
Do you have any ideas what is wrong or missing?
Thanks,
atticus
You're trying to parse using a pattern which will expect a comma (as it's in German) but you've given it a period ("0.459"). It looks like DecimalFormat stops parsing when it sees a character it doesn't understand. If you change it to "0,459" you'll see it parse correctly and then output "0.459". (I'm not sure whether System.out.println uses the system default locale, in which case it might print "0,459" depending on your locale.)
Note that you haven't tried to format the number at all in this code - only parse a number. If you want to format it, call format. The double itself doesn't have an associated format - it's just a number. It's not like parsing using a particular formatter returns a value which retains that format.
Here's code which will perform actual formatting of a double value:
DecimalFormat format = (DecimalFormat)NumberFormat.getInstance(new Locale("de"));
double value = 0.459;
String formatted = format.format(value);
System.out.println(formatted); // Prints "0,459"
EDIT: Okay, so it sounds like you're converting it from one format to another (from US to European, for example). That means you should probably use two different DecimalFormat objects - you could switch the locale between calls, but that sounds a bit grim to me.
I believe one way to parse and detect errors is to use the parse overload which takes a ParsePosition as well. Set the position to 0 to start with, and afterwards check that it's at the end of the string - if it isn't, that means parsing has effectively failed. I find it odd that there isn't a method which does this automatically and throws an exception, but I can't see one...
You may also want to set the parser to produce a BigDecimal instead of a double, if you're dealing with values which are more logically decimal in nature. You can do this with the setParseBigDecimal method.

Categories

Resources