Forcing decimal places on string
Hello,
I have a table where number are stored in varchar columns... below I show an example:
3000
4000
7200.45
5471.4
145.14
What I need is to get these values with 2 decimal places... as the result below:
3000.00
4000.00
7200.45
5471.40
145.14
How could I do this?
Thanks
Ranieri wrote:
When the column content is "0" the return will be ".00"... is there a way to force the return to be "0.00"?You want stripes? We got stripes.
You want plaids? We got plaids.
You want at least one digit before the decimal point? We got at least one digit beofre the decimal point.
TO_CHAR ( TO_NUMBER (txt)
, '999990.99' -- right-justifed
)or
TO_CHAR ( TO_NUMBER (txt)
, 'fm999999999999999999999999999999999990.00' -- left-justifed
)Just change '9.' to '0.'
Similar Messages
-
Displaying results with a decimal place of two. Forcing decimal place.
Hi there,
Im writing a simple calculation device.
You input one digit and press one of two buttons to multiply it by a certain number and then the result is displayed. The result is displyed hiding the result of the button you didn't press and visa versa.
I am having a problem displaying the result with a constant two decimal place.
I am using strings and thus don't know how to do this.
Here is my code:
import flash.events.MouseEvent;
//restrict the input textfield to only numbers
txtinput.restrict = "0-9";
//restrict the input textfield to only two characters
txtinput.maxChars = 6;
// event listeners
btnW.addEventListener(MouseEvent.CLICK, WHandler);
btnC.addEventListener(MouseEvent.CLICK, CHandler);
btnW.addEventListener(MouseEvent.CLICK, hideC);
btnC.addEventListener(MouseEvent.CLICK, hideW);
//functions
function WHandler (e:MouseEvent):void
//white calculation
var answerW:Number = Number(txtinput.text) * Number(0.90);
txtWResult.text = answerW.toString();
function CHandler (e:MouseEvent):void
//colour calculation
var answerC:Number = Number(txtinput.text) * Number(0.99);
txtCResult.text = answerC.toString();
function hideC (e:MouseEvent):void
//Hide colour result
txtCResult.visible = false;
txtWResult.visible = true;
function hideW (e:MouseEvent):void
//Hide white result
txtWResult.visible = false;
txtCResult.visible = true;
After having a look online I have found these two resources:
http://helpx.adobe.com/flash/kb/rounding-specific-decimal-places-flash.html
and
http://stackoverflow.com/questions/11469321/decimals-to-one-decimal-place-in-as3
But I am confused when combining these techniques with strings.
Any help would be greatly appreciated,
Thanks in advance
Mr BUse the toFixed() method of the Number class instead of the toString() method. The result of it is a String with the number of decimal places you specify.
var answerW:Number = Number(txtinput.text) * Number(0.90);
txtWResult.text = answerW.toFixed(2);
var answerC:Number = Number(txtinput.text) * Number(0.99);
txtCResult.text = answerC.toFixed(2); -
Force 2 decimal places with java.text.DecimalFormat
Hi all,
I am trying to force 2 decimal places for sum of 2 doubles (please see my code below). According to the API javadoc this should always display 2 decimals, however at the moment if the second decimal is zero it gets chopped off:(
Any ideas what is going wrong?
Thanks,
Olli
public double sum(double valueOne,double valueTwo)
double sum=valueOne+valueTwo;
DecimalFormat forceDecimals=new DecimalFormat("0.00");
total=Double.parseDouble(forceDecimals.format(sum));
return sum;
}Hi Olli,
you return sum and not total, but nevertheless returning a double doesn't help as 5.00 will always be 5.0.
An option would be to return the formatted String. -
Formatting Strings to two decimal places
When formatting double amounts to two decimal places, I looked up the procedure online and I have this so far:
public void calculatePayments()
double monthlyInterestRate = (Double.parseDouble(interestBox.getText())/12)/100;
double amountOfLoan = Double.parseDouble(balanceBox.getText());
double numberOfPayments = Double.parseDouble(yearsBox.getText()) * 12;
DecimalFormat Currency = new DecimalFormat("0.00");
double paymentAmount = (amountOfLoan * monthlyInterestRate) / (1 - Math.pow(1/(1 + monthlyInterestRate),numberOfPayments));
double formattedAmount = Currency.format(paymentAmount);
String s = Double.toString(paymentAmount);
tableBox.append(s);
tableBox.setText("Payment" + "\n" + "Number" + "\n");
for(int i = 0; i <= numberOfPayments; i++)
tableBox.append("" + i + "\n");
However, I get the following:
ProgramInterface.java:134: incompatible types
found : java.lang.String
required: double
double formattedAmount = (Currency.format(paymentAmount));
I'm trying to append the number to a text box (I'm making a loan calculator for my 155 class) Thanks for the helpString s = Currency.format(paymentAmount);Next time please paste your code between code tags exactly like this:
[code]
your code
[/code]
You can do that by simply pasting your code in the message area, highlight it and then click on the code button above.
You may read the [url http://forum.java.sun.com/help.jspa?sec=formatting]Formatting tips for more information.
Regards -
Formatting a Double to 2 decimal places without first converting to String
Hi,
Does anyone have any clear idea on how to format a Double directly without first converting it
to a String.I have just read through DecimalFormat/NumberFormat but I think there might be an easier way.I am also aware of printf(%f) and format(%f),but unfortunately am using Java 1.4 at the moment which does not seem to support them(will upgrade soon).The code I have is as follows:
public void displayAnalysis ()
System.out.println ("========================================================================");
System.out.println ("========================================================================");
System.out.println ("\nANALYSIS RESULTS FOR FILE " + inputFile + " \n");
System.out.println ("========================================================================");
System.out.println ("========================================================================");
System.out.println ("\nString length: "+ inputText.length());
System.out.println ("Ratio of printing to non-printing characters: "+ pRatio);
System.out.println ("Ratio of vowels to consonants: "+ vRatio);
System.out.println ("");
System.out.println ("Frequency of vowels as a percentage of number of printing characters;");
System.out.println ("Percentage of a's ="+ (NumberFormat.format(new DecimalFormat(((double)frequency[0]*100)/printable)))));
System.out.println ("Percentage of e's ="+ ((double)frequency[1]*100)/printable + "%");
System.out.println ("Percentage of i's ="+ ((double)frequency[2]*100)/printable + "%");
System.out.println ("Percentage of o's ="+ ((double)frequency[3]*100)/printable + "%");
System.out.println ("Percentage of u's ="+ ((double)frequency[4]*100)/printable + "%");
System.out.println ("Number of whitespace characters were " + whitespace);
System.out.println ("");
System.out.println ("========================================================================");
System.out.println ("========================================================================");
System.out.println ("");
System.out.println ("");
}I would like to display the frequencies to 2 decimal places.As a last resort I will have to alter the code to use DecimalFormat,but I'm hoping someone has a simpler solution.Oops,please ignore the line for the first frequency (a's),I was just playing around with trying to use NumberFormat!
-
i want to put a double into a JTextbox and i have it so it round down to a maximum of 2 decimal places. but if it only 12.3 for instance then thats what is put in the Textbox.
I want it so that it will round so there will always have 2 decimal places, for instance
12.3 would be 12.30
11 would be 11.00
14.242 woud be 14.24
Does anyone know a simple way of doing this?Hi Jos, i cant get it workin man heres my code
DecimalFormat df = new DecimalFormat("#.00");
temp = (Payable - Payable2) * 1.4;
temp = Double.parseDouble(df.format(temp));
tAPJPerUnit.setText("$" + temp);
It still just comes out as $1.4, any ideas?Do this:System.out.println("format: "+df.format(temp));and see what happens.
kind regards,
Jos -
Printing exactly 2 decimal places
I'm trying to print my double type variables to exactly 2 places. but numbers such as 3.00 and 124.00 keep printing as 3.0 and 124.0. Is there an easy way to force the printing to two decimal places on a primitive double type value without having to cast it to a Double object and playing around with NumberFormat and all that entails?
thanks much,
jhdarelln has exactly the right answer, except that you must do the thing you don't want to do. If it were me, I'd go with his example. It's less work and much cleaner.
import java.text.*;
public class DoubleTest {
static double[] numbers = {3000, 124.12, 123.122, 3.0, 124.0, 10.2, 12.14, 1234.55};
static final NumberFormat f = new DecimalFormat("#.00");
public static void main(String [] args) {
System.out.println("Goofy way!\n");
for (int i=0 ; i<numbers.length ; i++) {
printD(numbers);
System.out.println("\nRight way!\n");
for (int i=0 ; i<numbers.length ; i++) {
System.out.println(f.format(numbers[i]));
static void printD(double dbl) {
if (dbl % 10 == 0) {
System.out.println(dbl + "0");
} else {
String sdbl = "" + dbl;
String predot = sdbl.substring(0, sdbl.indexOf("."));
String atdot = sdbl.substring(sdbl.indexOf("."), sdbl.length());
String postdot = sdbl.substring(sdbl.indexOf(".") + 1, sdbl.length());
if (postdot.length() == 2) {
System.out.println(sdbl);
} else if (postdot.length() < 2) {
System.out.println(predot + "." + postdot.substring(0,1) + "0");
} else {
System.out.println(predot + "." + postdot.substring(0,2));
java DoubleTest
Goofy way!
3000.00
124.12
123.12
3.00
124.00
10.20
12.14
1234.55
Right way!
3000.00
124.12
123.12
3.00
124.00
10.20
12.14
1234.55
and the results are identical! -
Error while updating decimal places in general settings
Hii All
I have got an error while updating Decimal places in General Settings
Cannot update while another user is connected to the company i have checked, there is no other user logged in, i could add other settings but the problem is only with Decimal Places
Note : there are no postings yet, a fresh database for a new client
what could be the possible reason
thanks
RIYAZHiii All
As a forum rule, i have initially gone through with the existing threads and then i was force to post a thread,
would be helpfull if there is any other way..
Thanks
RIYAZ -
ToGB() decimal places
Hi All,
I have this piece of code which outputs the values to a html file.
(get-mailboxdatabase)|foreach-object {
$database= $_.name
$accounts= (get-mailbox -database $_.name).count
$size = (get-mailboxdatabase $_.name -status).databasesize.ToMB()/1024
add-content $wfile "<tr>"
add-content $wfile "<td align= 'center'>$database</td>"
add-content $wfile "<td align= 'center'>$Accounts</td>"
add-content $wfile "<td align= 'center'>$size</td>"
My issue I can't get the size to output to 2 decimal places it outputs 8 decimal places.
If I use ToGB() instead of ToMB()/1024 I only get the whole number
I have tried using {N0:02} but it doesn't help
What am I doing wrong?
TIA
AndyHow are you applying the format string?
$size = '{0:N2}' -f ((get-mailboxdatabase $_.name -status).databasesize.ToMB()/1024)
[string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " " -
Formatting currencies and decimal places
I'm currently using NumberFormat.getCurrencyInstance() to format numbers as currency. However, one problem I'm having is that I'd like values with no cents to be formatted with no decimal places, and any values with cents to be formatted with the usual 2 decimal places. For example:
17 would be formatted as $17
17.45 would be formatted as $17.45
17.4 would be formatted as $17.40
The last one is the tricky part--I've tried formatter.setMinimumFractionDigits(0), and this works great for the first two cases. But for the last case, the number gets formatted as $17.4.
Basically my problem is I want a number to be formatted with zero or two decimal places and nothing in between. Is there an easy way to do this?
Thanks in advance.Otherwise you are likely to find that you are getting .00 due to errors from previous calculations. You are right. Adjusted it to Locale aware
import java.text.FieldPosition;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.util.Locale;
public class SpecialCurrencyFormat extends NumberFormat {
private static final long serialVersionUID = 1L;
private final NumberFormat noDecimals;
private final NumberFormat decimals;
private final double maxDifference;
private final double factor;
public SpecialCurrencyFormat() {
this(Locale.getDefault());
public SpecialCurrencyFormat(Locale locale) {
decimals = NumberFormat.getCurrencyInstance(locale);
noDecimals = NumberFormat.getCurrencyInstance(locale);
noDecimals.setMaximumFractionDigits(0);
maxDifference = Math.pow(10, -decimals.getMaximumFractionDigits()) * .5;
factor = Math.pow(10, decimals.getMaximumFractionDigits());
@Override
public StringBuffer format(double number, StringBuffer toAppendTo,
FieldPosition pos) {
double adjustedValue = (Math.round(number * factor)) / factor;
if ((Math.abs(number - Math.round(number)) < maxDifference)) {
return noDecimals.format(adjustedValue, toAppendTo, pos);
} else {
return decimals.format(adjustedValue, toAppendTo, pos);
@Override
public StringBuffer format(long number, StringBuffer toAppendTo,
FieldPosition pos) {
return noDecimals.format(number, toAppendTo, pos);
@Override
public Number parse(String source, ParsePosition parsePosition) {
return decimals.parse(source, parsePosition);
public static void main(String[] args) {
NumberFormat nf = new SpecialCurrencyFormat(Locale.US);
double[] values = { 10000, 1000, 100, 10, 1, 10.1, 10.01, 10.001,
10.002, 10.003, 10.004, 10.005, 10.006, 10.007, 10.008, 10.009,
10.010 };
for (double value : values) {
print(nf, value);
private static void print(NumberFormat nf, double number) {
String formatted = nf.format(number);
try {
System.out.println(number + "\tas " + formatted + "\tand back "
+ nf.parse(formatted));
} catch (ParseException e) {
e.printStackTrace();
}The value adjustedValue is needed since NumberFormat doesn't seem to round the value. It just breaks.
Piet -
Ok so i know how to set decimal places in a applet and a command prompt type build but in a GUI i am trying to set them and it isnt working my code is:
doc.insertString(doc.getLength(), strFICA[j] + "\t", textPane.getStyle("regular"));
i went and added the information
Decimal Format twoDigits = new Decimal Format("000.0");
doc.insertString(doc.getLength(), twoDigits.Format (strFICA[j]) + "\t", textPane.getStyle("regular"));
it gives me the error cannot find symbol
symbol: method Format(java.land.String)
Lacation: Class java.text.DecimalFormat
doc.insertString(doc.getLength(), twoDigits.Format (strFICA[j]) + "\t", textPane.getStyle("regular"));
^
what does this mean and help will be greatHelp given here is voluntary and people do try hard, but your questions are as unintelligible as they are naive. You really need to do some ground work first by reading the tutorials and trying things out for yourself before posting here.
Those that get the most help are those that demonstrate they are willing to help themselves more than you seem to be. -
Decimal format to 2 decimal places ????
Hello Everyone,
I have created a web dynpro application which to display a report depending on the data given by the BAPI. But there is some issue with the numeric data returned by the BAPI.
For ex - if the BAPI returns 5.00 the value is displayed in the report as 5.
I want uniform decimal values till 2 decimal places. For example 5 shd come as 5.00, 2.1 shd come as 2.10 etc.
I searched SDN abt this, and found many threads relating to this.
I tried using decimal format, creating a simple dictinary type, but using all this what happens is the value basically changes to a string format, this implies that the value is displayed in the table as "left-aligned".
Where- as we need the decimal numeric values to be right-aligned.
Any thoughts how to achieve this.
Please correct me if I have missed out on anything.
Thanks,
SamtaHi,
From wat i understood.. u have a attribute coming from BAPI.. which you want to display with two decimal places,,
In this case.. assuming it is coming with 2 decimal places from the backend.. create a value node.. inside the node which contains the output data. set its carinality to 1..1 .. create a value attribute of type big decimal in it.. or probably string.. if there is an issue in displaying BigDecimal directly..
map this new attribute to the necessary column in the table..
BigDecimal value = new BigDecimal("the actual value in string or long").setScale(2);
assign this to the value attribute created..
(If alignment is the problem.. set the column 's textview property halign to right.. and layout as block or paragraph.. )
Regards
Bharathwaj
Message was edited by:
Bharathwaj R -
Rounding Doubles to Two Decimal Places
Hi All,
I've searched the archive and found a few different posts regarding restricting the number of decimal places in doubles. However they all suggest different methods, BigDecimal, NumberFormat etc.
Which is the simplest method of rounding a number say 10.023445656 to 10.02?
I tried using the java.text.NumberFormat but this turns the double into a string and I need the end result to be a double.
ThanksHi All,
I've searched the archive and found a few different
posts regarding restricting the number of decimal
places in doubles. However they all suggest different
methods, BigDecimal, NumberFormat etc.
Which is the simplest method of rounding a number say
10.023445656 to 10.02?
I tried using the java.text.NumberFormat but this
turns the double into a string and I need the end
result to be a double.
ThanksI ahve a small code that can do the work for u:
import java.text.*;
double format(double val, int dec){
double multiple=Math.pow(10,dec);
val=Math.round(val*multiple)/multiple;
DecimalFormat df=new DecimalFormat("0.00");
String format=df.format(val);
double dval=Double.parseDouble(format);
return dval;
}//end of functionHope that helps! -
How to change a double to 2 or less decimal places
hi
im trying to change a double to 2 decimal places
the reason is i have a angle that is sesitive to 1.0 x14
and it look rediculas to look at :)
i think on a calculater you use E exponents
but im unsure.There's a DecimalFormat class. And also Formattable interface. Classes implenting the latter can be formatted using a Formatter which employs the notation common in C and other languages.
String has a format() method that allows a formatted string to be produced, and there are numerous printf() methods in PrintWriter, Console etc
public class RoundingEg {
public static void main(String[] args) {
double pi = Math.PI;
// %.2f means "floating point number with 2 dp"
// %n means "ewline"
System.out.printf("%.2f%n", pi);
// or to obtain a string
String displayStr = String.format("%.2f", pi);
System.out.println("Used as any other string: " + displayStr);
} -
Hi,
I am trying to round the decimal place of number 0.105 as .11.
But it only rond up to 0.1 not 0.11.
I don't understand why it doesn't round to 0.11.
Can any one explain to me ?
My code :
import java.util.*;
import java.text.*;
import java.math.*;
public class TestFile {
public double number = .105;
public static void main(String[] args) {
TestFile test = new TestFile();
DecimalFormat aFormat = new DecimalFormat("#.##");
int decimalPlace = 2;
double num = .105;
BigDecimal bd = new BigDecimal(num);
bd = bd.setScale(decimalPlace,BigDecimal.ROUND_HALF_UP);
//DecimalFormat aFormat=new DecimalFormat("###.00");
String formattedString = aFormat.format(test.number);//format the String entered
System.out.println("formatted string: " + formattedString);
System.out.println("big decimal " +bd.doubleValue());
double formattedDouble = Double.parseDouble(formattedString);//convert to a double
System.out.println("back to a double: " + formattedDouble);
What should I do to round 0.11 ?
Thanks,
njan.BigDecimal bd = new BigDecimal(num);Change this line to
BigDecimal bd = new BigDecimal(Double.toString(num));Read the notes in the API for BigDecimal constructor that accepts double.
http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigDecimal.html#BigDecimal(double)
The results of this constructor can be somewhat unpredictable...
Maybe you are looking for
-
Need help with IDOC CREMAS_03 mapping
i was not able to figure out what values to assign to the following mandatory fields. BEGIN EDI_DC40(node not mandatory) SEGMENT TABNAM DIRECT IDOCTYP MESTYP SNDPOR SNDPRT SNDPRN RCVPOR RCVPRN i am trying to map the following structure to the CREMAS_
-
Java EE 5 @ Worldwide state?
Hi, It is really great to have this forum here and great to have a certified and fully compliant with the latest Java EE 5 standard implementation at SAP. I wonder does anyone know if there is another vendor that has achieved this major success so fa
-
I have Office 365 Home edition. I am trying to use Lync but in my Outlook I have no icon to set up an Online Meeting. I have followed instructions to look in add-ons for this functionality but I can see nothing that will help. Do I need to upgrade to
-
Nokia 6085, PC Suite and Windows 2000
I can't find the PC Suite version that will work with my phone and Windows 2000. Can someone point me to where it is so I can download it please?
-
Is there an AIM for mac?
Is there an AIM download for Mac, if so where can I download it?