Limit decimal place
Hello, I am totally new to Java,
Basically I am subtracting 2 numbers, (2 floats)
How do I limit the answer to just 2 decimal places , so the answer is something like 1.45 , .45 and so on ?
i like this (The Sue will not mind, i guess :))
* -description :<p> Sets the number of decimal places to the argument specified
* the class is overloaded to return float and double data types. The parameter
* named 'places' is the number of decimal places returned by the method.
* Note: the parameter int will also work (without amendment) for byte and short.</p>
* // <b>EXAMPLE:</b><br>
* <code>
* double d = 1.250550123456789;
* System.out.print( Fraction.digits(d,4) );
* // will output the double as : 1.2506
* float f = (float)1.2505012;
* System.out.print( Fraction.digits(f,3) );
* // will output the double as : 1.251
* </code>
* This has the advantage over other methods in that the data type retains its
* integrity as a double or a float data-type, instead of converting it to a String
* as in java.text.DecimalFormat and rounding off the additional data.<br>
* The class could be also used to avoid the pitfalls of floating point
* innacuracies;<br>
* // <b>EXAMPLE:</b><br>
* <code>
* double d1 = 3.0 * 0.1;
* System.out.println(d1*10);
* // will output : 3.0000000000000004
* double d2 = 3.0 * 0.1;
* byte b = (byte)14; // works with other data type widths
* System.out.println(Fraction.digits(d2*10, b)); // slice off the last digit
* // will output : 3.0
* </code>
* @author Sum-shusSue
public class Fraction {
public static double digits(double d, int places) {
return (long)(d*Math.pow(10,places)+0.5)/Math.pow(10,places);
public static double digits(double d, long places) {
return (long)(d*Math.pow(10,places)+0.5)/Math.pow(10,places);
public static float digits(float d, int places) {
return (int)(d*Math.pow(10,places)+0.5)/(float)Math.pow(10,places);
public static float digits(float d, long places) {
return (int)(d*Math.pow(10,places)+0.5)/(float)Math.pow(10,places);
}
Similar Messages
-
How can I limit a double value to two decimal place?
How can I limit a double value to two decimal place?
Java keeps on adding zero's to a simple double subtraction:
1497 - 179.64 = 1317.3600000000001The answer must have been simply: 1317.36If the trouble is with output ...
If the trouble is with value accuracy ...The trouble is with OPs understanding of and/or expectations of IEEE 754 floating point numbers. o_O
[And it's probably a view (output) issue.]
how can i actually use numberformat to cut those
unwanted decimal places?Read the API - Puce already provided the link. -
Trying to limit the fidelity (to 2 decimal places) of a calculated value?
Hi Everyone,
I have a column that shows the Profit / Loss % for items sold.
ISNULL(((T0.LineTotal - T0.StockValue) / NULLIF(T0.StockValue, 0)) * 100, 0
Because it is possible for StockValue to be a zero (0) amount in our system it was necessary to add the NULLIF function.
If a NULL value is detected then a value of 0 is ultimately returned. Due to the fact that there could still be a profit or a loss in this column I needed to add 'N/A', which I achieved by casting the calculation to a varchar and then applying a CASE statement, the full syntax is as follows -
CAST(ISNULL(((T0.LineTotal - T0.StockValue) / NULLIF(T0.StockValue, 0)) * 100, 0) AS varchar) = '0.00000000000000' THEN 'N/A'
ELSE CAST(ISNULL(((T0.LineTotal - T0.StockValue) / NULLIF(T0.StockValue, 0)) * 100, 0) AS varchar) END
AS 'Profit / Loss %'
My challenge is that the % for profit has an excessive level of fidelity, it currently goes to 14 decimal places (e.g.: 134.43223443223443)!
I would like to limit the fidelity to 2 decimal places (e.g: 134.43). I have attempted to do this by 'double casting', first casting to a decimal then to a varchar (to allow for the 'N/A') -
CAST(CAST(ISNULL(((T0.LineTotal - T0.StockValue) / NULLIF(T0.StockValue, 0)) * 100, 0) AS decimal) AS varchar)
In this case the fidelity is not sufficient, and I lose all decimal places. If I stipulate the nature of the decimal place, e.g.: decimal(4,2), then I get an "arithmetic overflow" error.
How can I make my results either 'N/A' or a numeric result (with 2 decimal places)?
Any help will be greatly appreciated.
Kind Regards,
DavidHi David...
Check this
* Purpose: Lists the Sales History of Items by (user designated):
* Item Code (range) and / or
* Whs Code (range) and / or
* Industry Code and / or
* BP (Customer Code)
DECLARE @begItemCode nvarchar(20), @endItemCode nvarchar(20), @whsCode nvarchar(5), @indCode nvarchar(5), @custNo nvarchar(10)
SET @begItemCode = ''
IF @begItemCode = ''
SET @begItemCode = '00%'
SET @endItemCode = '' + 'Z'
IF @endItemCode = 'Z'
SET @endItemCode = 'ZZ%'
SET @whsCode = ''
IF @whsCode = ''
SET @whsCode = '%'
SET @indCode = ''
IF @indCode = ''
SET @indCode = '%'
SET @custNo = 'C000002'
IF @custNo = ''
SET @custNo = '%'
select tt.[Document Date],tt.[Document No.],tt.[Doc Type],tt.[Cust Code],tt.[Customer Name],tt.[Item Code],tt.[Item Description] ,
tt.whscode, tt.[Line Net],tt.[Line Cost],tt.[Itm Avg Cost] , tt.[Profit / Loss],
cast(round(tt.[Profit / Loss %],2,0) as decimal(18,2) ) as 'PL%',tt.[Vendor Name],tt.[Salesman Name] from (
SELECT
T1.DocDate AS 'Document Date'
, T1.DocNum AS 'Document No.'
, 'Invoice' AS 'Doc Type'
, T1.CardCode AS 'Cust Code'
, T1.CardName AS 'Customer Name'
, T0.ItemCode AS 'Item Code'
, T0.Dscription AS 'Item Description'
, T0.Quantity AS 'Ship Qty'
, T0.WhsCode
, T0.LineTotal AS 'Line Net'
, T0.StockValue AS 'Line Cost'
, T2.AvgPrice AS 'Itm Avg Cost'
, (T0.LineTotal - T0.StockValue) AS 'Profit / Loss'
, CASE WHEN
--ROUND(
CAST(ISNULL(((T0.LineTotal - T0.StockValue) / NULLIF(T0.StockValue, 0)) * 100, 0) AS varchar) = '0.00000000000000' THEN 'N/A'
ELSE CAST(ISNULL(((T0.LineTotal - T0.StockValue) / NULLIF(T0.StockValue, 0)) * 100, 0) AS varchar) END
AS 'Profit / Loss %'
, T4.CardName AS 'Vendor Name'
, T5.SlpName AS 'Salesman Name'
FROM dbo.INV1 T0
INNER JOIN dbo.OINV T1 ON T1.DocEntry = T0.DocEntry
INNER JOIN dbo.OITM T2 ON T2.ItemCode = T0.ItemCode
INNER JOIN dbo.ITM1 T3 ON T3.ItemCode = T0.ItemCode AND T3.PriceList = 1
INNER JOIN DBO.OCRD T4 ON T4.CardCode = T2.CardCode
INNER JOIN DBO.OSLP T5 ON T5.SlpCode = T1.SlpCode
WHERE T1.DocType = 'I' AND T2.OnHand > 0 AND T0.ItemCode >= @begItemCode AND T0.ItemCode <= @endItemCode AND T0.WhsCode LIKE @whsCode
AND T2.U_SCE_IN_Industry LIKE @indCode AND T1.CardCode LIKE @custNo
UNION ALL
SELECT
T10.DocDate AS 'Document Date'
, T10.DocNum AS 'Document No.'
, 'Credit' AS 'Doc Type'
, T10.CardCode AS 'Cust Code'
, T10.CardName AS 'Customer Name'
, T9.ItemCode AS 'Item Code'
, T9.Dscription AS 'Item Description'
, -1 * T9.Quantity AS 'Ship Qty'
, T9.WhsCode
, -1 * T9.LineTotal AS 'Line Net'
, -1 * T9.StockValue AS 'Line Cost'
, T11.AvgPrice AS 'Itm Avg Cost'
, -1 * (T9.LineTotal - T9.StockValue) AS 'Profit / Loss'
, CASE WHEN
CAST(ISNULL(((T9.LineTotal - T9.StockValue) / NULLIF(T9.StockValue, 0)) * -100, 0) AS varchar) = '0.00000000000000' THEN 'N/A'
--ELSE CAST(CAST(ISNULL(((T9.LineTotal - T9.StockValue) / NULLIF(T9.StockValue, 0)) * -100, 0) AS decimal) AS varchar) END
ELSE CAST(ISNULL(((T9.LineTotal - T9.StockValue) / NULLIF(T9.StockValue, 0)) * -100, 0) AS varchar) END
AS 'Profit / Loss %'
, T13.CardName AS 'Vendor Name'
, T14.SlpName AS 'Salesman Name'
FROM dbo.RIN1 T9
INNER JOIN dbo.ORIN T10 ON T10.DocEntry = T9.DocEntry
INNER JOIN dbo.OITM T11 ON T11.ItemCode = T9.ItemCode
INNER JOIN dbo.ITM1 T12 ON T12.ItemCode = T9.ItemCode AND T12.PriceList = 1
INNER JOIN DBO.OCRD T13 ON T13.CardCode = T11.CardCode
INNER JOIN DBO.OSLP T14 ON T14.SlpCode = T10.SlpCode
WHERE T10.DocType = 'I' AND T9.ItemCode >= @begItemCode AND T9.ItemCode <= @endItemCode AND T9.WhsCode LIKE @whsCode
AND T11.U_SCE_IN_Industry LIKE @indCode AND T10.CardCode LIKE @custNo
) as tt
Hope Helpful
Regards
Kennedy -
Limit a float value to single decimal place after round off
41.231445 is float value . How can I limit this to a single decimal place after round off?
ie; 41.2
Any help in this regard will be well appreciated with dukes.
Regards,
AneesAlso read this: [http://java.sun.com/docs/books/tutorial/i18n/format/decimalFormat.html]
-
Help wanting to limit output to 2 decimal places :O
im trying to make it so i only output over 2 decimal places.
here is my code. can someone tell me what to add? thank you mucho
package javaapplication2;
import java.util.*;
import cs1.Keyboard;
public class Main {
public static void main(String[] args) {
double Hours_Worked,
Hourly_Wage,
Total_Money;
final double COMMISSION = 3.59 * .1;
int noSoldFish;
String UserName;
System.out.println("Please enter the employee's name: ");
UserName = Keyboard.readString();
System.out.println("Please enter hours worked by employee: ");
Hours_Worked = Keyboard.readDouble();
System.out.println("Enter employee's hourly wage: $");
Hourly_Wage = Keyboard.readDouble();
System.out.println("Enter the number of fish sold by employee:");
noSoldFish = Keyboard.readInt();
Total_Money = Hours_Worked * Hourly_Wage + noSoldFish * COMMISSION;
System.out.println("\n===========================================" +
"\n Employee's Information" +
"\n===========================================" +
"\n" + UserName + " worked " + Hours_Worked + " hours this week" +
"\n" + UserName + " makes $" + Hourly_Wage + " per hour." +
"\nThe total salary and commission for "
+ UserName + " is $" + Total_Money);
System.exit(0);
}read up on, or search the forum on NumberFormat and in particular the factory method NumberFormat.getCurrencyInstance(); This is what you need here.
-
Hi,
How do you limit the number of decimal places which are displayed by a double??
Cheers
Davidhttp://java.sun.com/docs/books/tutorial/i18n/format/index.html
-
Managing decimal places in MD04
Hi,
We have our system set in transaction CUNI that the decimal places are 0 for UOM LBS.
However we want to see decimals some times in MD04. Is this possible through some user parameters or so with out changing the system customizing in CUNI?
Thanks.I don't think so. I also fail to understand why you would change the standard settings, and limit the decimal places of a physical UOM like LBS.
-
Decimal place for qualitative characterstics
i have lot with 01 inspection type ,quantity 1.5 Litres,its a qualitative MIC with classed recording ,while result recording for this
quantity to be Accepted are rejected and partialy accepted,while entering the values i.e 1.5 its giving a error that is no decimal places are allowed,i checked all the Base units its all in Litres,how i overcome this type issue,Yes system behaves as per setting you have done
1.You have selected Qualitative Char ,it means you should enter "accepted or rejected" etc.
but you have entered 1.5 this is a "Quantitative Value"
2.So You have make this char as "Quantitative" ,select the upper limit ,lower limit ,base value along with decimal places(say 2).
this will allow you to enter value 1.5 or 1.50 etc -
is there a way to limit the number of decimal places that appear in an output?
Yes, truncate it manually or by some input method limiter.
If you are reading a spreadsheet file and outputting that to the console, then you can simply check the value of the string, and determine how many numbers come after the "." charactor. That will give you an index in the string.
Using that index you can then simply create a new string including the whole number, decimal, and only those points that you want.
You can also do the reverse and expand the decimals from, let's say 1 decimal (like 10.2) to a 2-digit decimal (like 10.20) by simply adding the needed places in the string after the last charactor. -
Limiting AS distance to two decimal places
I am just about there getting the Google Maps API talking to my SQL database. For my search results I have the SQL:
SELECT *, ( 3959 * acos( cos( radians(" .$POST["latitude"] .") ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(" .$POST["longitude"] .") ) + sin( radians(" .$_POST["latitude"] .") ) * sin( radians( lat ) ) ) ) AS distance FROM VenuesGeocodes1 HAVING distance < 100 ORDER BY distance LIMIT 0 , 30;
Which works great, but displays the distance with 15 decimal places which is complete overkill.
How can I limit that to just two decimal places? I thought I just needed to change distance to distance (10,2), but it didn't like it.
If anyone can let me know what it should be that would be much appreciated.
Thanks.Thanks Rob - I also got it to work using ROUND in the query:
SELECT *, ROUND( 3959 * acos.... -
my cost per month textbox typically returns multiple decimal places, is it possible to limit it's output to two decimal places like real monetary calculations?
calculatebutton.addEventListener(MouseEvent.CLICK, doMyCalculation);
calculatebutton2.addEventListener(MouseEvent.CLICK, doMyCalculation2);
costpermonth.restrict = ".0-9";
var myAnswer : Number;
myAnswer = Number(costofitem.text) - Number(amountsaved.text);
amountneedtosave.text = String(myAnswer);
function doMyCalculation2(e:MouseEvent):void
var myAnswer2 : Number;
myAnswer2 = Number(amountneedtosave.text) / Number(howmanymonths.text);
costpermonth.text = String(myAnswer2);use the toFixed() method of numbers:
amountneedtosave.text = myAnswer.toFixed(2); -
2 Decimal Places (that's all)
My output from my calculations is:
2.74594
1.343434343434
14.4758395065893849
How can I limit my digits after the decimal point to only 2 places?
Above answers would be:
2.74
1.34
14.47
Would appreciate any help.Well your code does exactly what you say it will ;-)
It truncates the number to just 2 places.
But if you want to get the "standard" behaviour of ROUND_HALF_UP then you should use Math.round(), as can be seen in the following.for (int i = 0; i < 100; i++) {
double d = 2.74594 * i;
double d2 = d;
double d3 = d;
//this code truncates to 2 decimal places
d2 = d > 0 ? Math.floor(d * 100) / 100.0 : Math.ceil(d * 100) / 100.0;
d3 = Math.round(d * 100) / 100.0;
System.out.println("d = " + d + "\td2 = " + d2 + "\td3 = " + d3);
}I usually leave doubles at their default precision until I need to presist or present them(to a db for instance), and then I use a class along the following lines...class Formatter {
public static final int DEFAULT_PRECISION = 2;
public static final String DEFAULT_PATTERN = "#.00";
public static final String ZEROS = "0000000000000000";
public static String convertDoubleToString(Double d) {
return convertDoubleToString(round(d, DEFAULT_PRECISION), DEFAULT_PATTERN);
public static String convertDoubleToString(double d) {
return convertDoubleToString(round(d, DEFAULT_PRECISION), DEFAULT_PATTERN);
public static String convertDoubleToString(Double d, int precision) {
return convertDoubleToString(round(d, precision), "#." + ZEROS.substring(precision));
public static String convertDoubleToString(double d, int precision) {
return convertDoubleToString(round(d, precision), "#." + ZEROS.substring(precision));
public static String convertDoubleToString(Double d, String pattern) {
return new DecimalFormat(pattern).format(d.doubleValue());
public static String convertDoubleToString(double d, String pattern) {
return new DecimalFormat(pattern).format(d);
private static final double round(Double d, int precision) {
double factor = Math.pow(10, precision);
return Math.round((d.doubleValue() * factor)) / factor;
private static final double round(double d, int precision) {
double factor = Math.pow(10, precision);
return Math.round((d * factor)) / factor;
} -
I am using Captivate 5.5, I have a custom variable (vtime), and I would like to show the time out to hundreths of a second. Captivate outputs to more than 2 decimal places.
Is there way to limit to only 2 decmal places without programming?I'm sorry, but the answer is NO. This is fixed in Cp6 but that doesn't help you of course.
Lilybiri -
I need to key in a number that contains at least 17 decimal places using numeric digit control and i need to use expression note as well. Can anyone help?
After laying down a numeric control right click on it and select "Format and Precision..." to change the number of decimal places. You can also right click and change the "Representation" of the numeric control. By default it will be a DBL which is a 64 bit decimal number with an approximate range of 10**(-308) to 10**308. This is about 15 decimal digits of precision. I know SGL will only give you 10**(-38)to 10**38, which is about 7 decimal digits of precision. Neither of these will cut it for what you are trying to do.
I would recommend using the Extended Precision (EXT) representation. According to the linked document La
bVIEW's implementation of the Extended Precision follows the IEEE 80-bit spec(on Windows OSes). Supposedly even the IEEE 128-bit spec(not implemented on the Windows OSes)only gets you 19 decimal places but I am not sure what the limitations of LabVIEW's implementation are. (I found a good table in the LabVIEW help title, "Numeric Data Types Table".)
I was able to successfully get 17 digits after the decimal point but that was with a leading 0 only before the decimal point. I think you may just be approaching the limit of how a number can be represented in this programming language.
Anyone else?
-scraggs99 -
Dear friends
System is not accepting decimal places entered in Target values, Upper limit & lower limit of MIC in QS21. Only whole numbers are accepted. Also what is the meaning of upper plausibility limit & lower plausbility limits and what are their uses. Please guide.
SelvaSelva
your target is 100 and upper plaus limit 2 --- system will accept upto 102 and if you enter 102.1 Rejected
Lower plaus limit 1 -
> less than 99 -
rejected
Let me know if it is not clear
thanks
Sami
Maybe you are looking for
-
Software Updates Missing and File Not opening in Final Cut Pro
Hi Experts, I am having trouble with Final Cut Pro. Here goes:- I tried to load up a FCP file called "Overview" in Lesson One of the Apple Pro Training Series book called "Color". The file would not open and I got the following message alert in FCP:
-
Hello Community Using Visual Studio 2008 I have created a Windows Forms Application in which I created Embedded Reports (rdlc). The embedded reports (rdlc) uses Matrix(s). Now on this one rdlc I have dragged 2 Matrix(s) onto the body.
-
Clamshell mode vs. open
Hi everyone, Does someone know which mode is better/healthier, for my macbook pro? Clamshell mode or open mode? Both with an external display. Greets, jan
-
Hi, does anyone know if there is existing listing report for all created standard wbs element? please advise. thanks
-
Workflow: XML Container not updated
Hallo Gurus! I am starting a new workflow with SWW_WI_START_SIMPLE. After that i change some container values with following code: *Workflow starten CALL FUNCTION 'SWW_WI_START_SIMPLE' EXPORTING * CREATOR = ' ' *