Given a number x.
how do i put that number in () if it was negative.
for example: x = -725.21 =>> result = (725.21)
thanks
Printable View
Given a number x.
how do i put that number in () if it was negative.
for example: x = -725.21 =>> result = (725.21)
thanks
What have you got so far?
Much luck with this.
This is what i got so far...
Code:public double printCurrencyStyle(double amount)
{
double result = 0;
System.out.printf("$ %,.2f", amount);
if (amount < 0)
System.out.printf("$ %,.2f", + (amount));
return result;
}
and heres the result...
Testing method printCurrencyStyle in student class MidtermProblems
--------------------------------------------------------------------------------
X printCurrencyStyle(-795.152)-> expected:<$ [(795.15)]> but was:<$ [-795.15]>
--------------------------------------------------------------------------------
9/10 tests passing (90%)
Should the method return a String representation of the number as it is to be displayed (i.e., with parenthesis if < 0) rather than return a double?
How do i use the replace mothod to replace("-", "") inside a function?
By changing the number from a negative to a positive.Quote:
How do i use the replace mothod to replace("-", "") inside a function?
But please answer my question that I asked previously: is the method in fact supposed to return a String representation of the number and not a double as it is currently written?
it supposed to return a double!
If it were to return a String though, I'd do it like so:
Code:public static String printCurrencyStyle(double amount)
{
NumberFormat currFormat = NumberFormat.getCurrencyInstance();
String result = "";
if (amount < 0) {
result = "(" + currFormat.format(-amount) + ")";
} else {
result = currFormat.format(amount);
}
return result;
}
I do have to mention that you should consider improving your thread title if you post here again. You want the thread title to be helpful to us, to tell us extremely briefly what your current problem is. Since 99% of folks who start threads here "need help", this title isn't helpful. A better one would be "How to print negative numbers in parenthesis"
i'll keep that in mind.thanks
Quote:
X printCurrencyStyle(-795.152)-> expected:<$ [(795.15)]> but was:<$ [-795.15]>
I'm not sure I exactly understand this. Where is the $ supposed to come? If it's outside the number you can use:
Code:public class FormatEg {
public static void main(String[] args) {
System.out.println(printCurrencyStyle(-42d));
System.out.println(printCurrencyStyle(0d));
System.out.println(printCurrencyStyle(100.666));
}
static String printCurrencyStyle(Double d) {
return String.format("$%(.2f", d);
}
}