Calculating Percentages using int
Hi,
How would I calculate a percentage when the initial values I have are int primitives, so that the percentage is rounded to the nearest whole number. i.e. 4/6 equates to 67%
Thanks in Advance.
int x = 4;
int y = 6;
int percentage = (int) (Math.rint(x * 100.0 / y));
Similar Messages
-
Calculating percentages using numbers
Hi there,
I hope someone out there can help me but how do I calculate the percentage of two numbers using Numbers. For example £4000 incoming and £1650 outgoings - How do I get the spreadsheet to work out the percentage and input this number into the fields? This is really painful trying to work it out. ThanksHi Adrian,
You wrote: "I need to do this with 2 column actually A and B, both column need to be added by that 5%, I think this only possible"
If I'm reading the description of your table correctly, column A shows the number of units, column B the price of each unit, and column C the price of that quantity of units.
If you increase the unit price by 5%, that will also increase the total price of n units by 5%, provided you multiply the quantity by the new unit price instead of the old unit price.
Here's a step by step:
Original table:
Formula in C2, and filled down column C: =A*B
Add a new column (D) to hold the formula for the increased price.
D2, and filled down: =B*(1+5%)
With the cells shown still selected, Copy (command-C)
Now select cell B2, and go Edit > Paste Values (Numbers '09) or Edit > Paste Formula Results (Numbers 3)
Results should be as shown below:
(Note that column C has been recalculated to show the results of a 5% increase in unit prices. Column D (labelled "temp") has also been recalculated to show what the unit prices would be after a second 5% increase. the last step is to delete this column, leaving us with the original table, but with unit prices increased by 5%:
In practice, you would probably NOT do this on the actual invoice. Item names (or numbers) and the unit prices of those items would be kept on a price list, separate from the invoice, and the price would be looked up by the Invoice table when the item name or number was entered. The table would be used as an invoice generator, and the completed invoices either printed or 'printed' as pdf files as each was generated.
Price changes would be made on the price list, either individually, or geerally as done here. Note that the new prices would affect new invoices AND any existing invoices still connected to the price list (which is why each is 'printed' to separate it from the calculating document). Here's a simple example using a price list as a lookup table. Item Number and Quantity are entered on the invoice. The rest is added by formulas.
Formulas:
Price List has no formulas.
Invoice:
C2 and filled right to column D and down to row 6:
=IFERROR(VLOOKUP($B,Price List :: $A:$C,COLUMN()-1),"")
In row 6, the empty cell in column A will cause a "could not find" error. IFERROR catches this and places a null string in C6 (and in D6).
E2 and filled down to E6: =IF(LEN(D)<1,"",A*D)
LEN(D) returns the length (in number of characters) of the contents of the cell on the same row of column D. If the cell is empty, or contains a null string (as in row 6), the length is zero, and IF will place a null string in column E.
SUM, in row seven, interprets text (including a null string) as zero, so this does not affect the sums in coumns A and E.
Row 7 is a Footer Row. Formulas referencing a whole column ignore values in Header and Footer rows, making it possible to place the formulas below where they are.
A7: =SUM(A)
E7: =SUM(E)
Regards,
Barry -
Calculated Percentage Columns in Pivot Table loose formating in Excel
I have a simple report built using pivot table ( OBIEE 11.1.1.5.0)
1 Metric and 1 dimension using pivot table. and I duplicated the metric column and change it to % column.(Show data as % of column). SO far so good. Below is the snapshot
http://tinypic.com/r/2s14xa9/7
Now i download the report in excel and all the % values are messed up . Below is how it looks
http://tinypic.com/r/bede90/7
I tried messing with data formats etc..nothing works.. I cannot add a custom column format to the metric column since it will impact the derived % column.
Is this a bug ?Any pointers ..
ThanksHi,
Follow up this SR:
SR 3-5060435331: Calculated Percentage Columns in Pivot Table loose formating in Excel
Workaround: (not sure may be give a try)
also give a try like below one then try to download it may work.
In that % column -->add the below statement in the Custom CSS section of the column properties:
mso-number-format:"\@"
Refer snapshot here:
http://i53.tinypic.com/a09kqv.jpg
This will treat the data in the column as text while downloading to excel, hence retaining any leading or trailing spaces.
Thanks
Deva -
Introduction
In SQL Server Analysis Services (SSAS), you can create a calculated measure in SQL Server Data Tool (SSDT)/Boniness Integrated Development Studio (BIDS). Sometimes you may need to create calculated measure by using AMO in a C# or VB project.
In this article, I will demonstrate so how to create calculated measure using AMO in SSAS?
Prerequisites
Before create calculated measure using AMO, you need to ensure that the following components were installed in your server.
The multidimensional database AdventureWorks Multidimensional Model 2012
A SQL Server with SSIS and SSAS installed
The AMO libraries installed:
X86 Package (SQL_AS_AMO.msi)
X64 Package (SQL_AS_AMO.msi)
Solution
Here is the detail steps to create calculated measure using AMO in SSAS.
Open SSDT and create a new SSIS project.
Drag Script Task to the design surface.
Click SSIS-> Variables to open the Variables window and add two variables that used to connect to the server and database.
Create a connection to connect to SSAS server.
Rename the connection name to ssas.
Double click the Script Task to open Script Task Editor.
Add Connection and Database variables to ReadWriteVariables textbox and then click Edit Script button.
Add AMO reference in the Solution Explore window.
Copy the script below and paste it into the script.
Dim objServer As Server
Dim objDatabase As Database
Dim strDataBaseID As String
Dim objCube As Cube
Dim objMdxScript As MdxScript
Dim objCommand As Command
Dim strCommand As String
objServer = New Server
objServer.Connect("localhost")
objDatabase = objServer.Databases("AdventureWorksDW2012Multidimensional-EE2")
strDataBaseID = objDatabase.ID
If objDatabase.Cubes.Count > 0 Then
objCube = objDatabase.Cubes("Adventure Works")
If objCube.MdxScripts.Count > 0 Then
objMdxScript = objCube.MdxScripts("MdxScript")
objMdxScript = objCube.MdxScripts(0)
Else
objCube.MdxScripts.Add("MdxScript", "MdxScript")
objMdxScript = objCube.MdxScripts("MdxScript")
End If
objCommand = New Command
strCommand = "CREATE MEMBER CURRENTCUBE.[Measures].[Multipy Measures By 3]"
strCommand = strCommand & " AS [Measures].[Internet Sales Amount] * 3, "
strCommand = strCommand & " VISIBLE = 1 ; "
objCommand.Text = strCommand
objMdxScript.Commands.Add(objCommand)
objMdxScript.Update()
objCube.Update()
End If
objServer.Disconnect()
Then you can run this SSIS package to create the calculated measure.
Applies to
Microsoft SQL Server 2005
Microsoft SQL Server 2008
Microsoft SQL Server 2008 R2
Microsoft SQL Server 2012
Please click to vote if the post helps you. This can be beneficial to other community members reading the thread.Thanks,
Is this a supported scenario, or does it use unsupported features?
For example, can we call exec [ReportServer].dbo.AddEvent @EventType='TimedSubscription', @EventData='b64ce7ec-d598-45cd-bbc2-ea202e0c129d'
in a supported way?
Thanks! Josh -
When i try to open a pdf using int exp i get a message that it has encountered a problem and will cl
when i try to open a pdf using int exp i get a message that it has encountered a problem and will close
Internet explorer. I have adobe reader and flash player which I uninstalled and reinstalled. I tried another browser and the pdf's open so it is a problem with IE .Thanks for your comments.
[private data removed] -
How to calculate any two date with diffence calculation by using obiee11g?
Hi,
i have a requirement like,
location wise current month and previous month with movement calculation,can to tell me how to calculate any two date with diffence calculation
by using obiee11g
Note,
I tried to implemented ago function as well as dynamic two dates calculation using $2-$1 methods..but i am getting the o/p it's self i am getiing some null value also that' why it's not tallying with our actual report.
i tired to used ifnull(mesaurecolumn,0) also case condition on the mesaure colution still it's not tallying.
THanks and Rds,
Devarasu.RHi,
for Date Difference........
TimestampDiff(interval, timestamp1, timestamp2)
ex:TimestampDiff(SQL_TSI_DAY, cast('1-apr-2011' as date), current_date)
Where:
interval
The specified interval. Valid values are: SQL_TSI_SECOND, SQL_TSI_MINUTE, SQL_TSI_HOUR, SQL_TSI_DAY,
SQL_TSI_WEEK, SQL_TSI_MONTH, SQL_TSI_QUARTER, SQL_TSI_YEAR.
Cheers,
Aravind -
Why does the Java API use int instead of short or byte?
Why does the Java API use int if short or even byte would be sufficient?
Example: The DAY_OF_WEEK field in Calendar uses int.One of the point is, on the benchmark tests on Java performance, int does far better than short and byte data types.
Please follow the below blog talks about the same.
Java Primative Speed
-K -
Is calculator cache used if there are no blocks created?
Hi experts,
In DBAG it is written -
Essbase can create a bitmap, whose size is controlled by the size of the calculator cache, to record and track data blocks during a calculation. Determining which blocks exist using the bitmap is faster than accessing the disk to obtain the information, particularly if calculating a database for the first time or calculating a database when the data is sparse.
If my calculation does not create any block (it is only dense calculation), but it reads from different blocks on the right hand side of assignment (using cross dim) then is calculator cache used? Is it better to turn off cache in the calculation?
~DebashisThe very next lines in the DBAG entry you quoted from are...
Essbase uses the calculator cache bitmap if the database has at least two sparse dimensions and either of these conditions is also met:
You calculate at least one full sparse dimension.
You specify the SET CACHE ALL command in a calculation scriptSo I would assume the answer is 'no', unless your dense-only calculation also contains 'SET CACHE ALL'. -
Why use int over double?
i am using the book beginning java 2. and there is a example showing how the math class works
the program calculates the radius of a circle in feet and inches given that the area is 100 square feet:
public class MathCalc
public static void main(String[]args)
double radius = 0.0;
double circlearea= 0.0;
int feet = 0;
int inches = 0;
radius = Math.sqrt(circleArea/Math.PI);
feet = (int)Math.floor(radius);
inches = (int)Math.round (12.0 * (radius-feet));
System.out.println( Feet + "feet" + inches + "inches");
the output will be 5 feet 8 inches.
my question is why bother with using 'int', why not simply use 'double' for all your variables?
in feet and inches 'int' has been used as the result would have been a floating value. so casting as been used. But doesnt that complicate things?cant one just use long for all variables and forgot about worrying whether the value will fit or not.
thanks
Alii am using the book beginning java 2. and there is a
example showing how the math class works
the program calculates the radius of a circle in feet
and inches given that the area is 100 square feet:
public class MathCalc
public static void main(String[]args)
double radius = 0.0;
double circlearea= 0.0;
int feet = 0;
int inches = 0;
radius = Math.sqrt(circleArea/Math.PI);
feet = (int)Math.floor(radius);
inches = (int)Math.round (12.0 *
d (12.0 * (radius-feet));
System.out.println( Feet + "feet" + inches +
"inches");
the output will be 5 feet 8 inches.
my question is why bother with using 'int', why not
simply use 'double' for all your variables?There are several reasons to use int (when appropriate) rather than double. More generally, there are several reasons to use integer arithmetic instead of floating point.
First, integer arithmetic is precise whereas floating point arithmetic is always subject to imprecision. E.g. 6 / 2 always equals 3, 6.0 / 2.0 may equal something like 3.000000000000001.
Second, (related to the above) the results of integer arithmetic operations will not vary from one machine to the next. The results of the same floating point operation may vary from one machine to the next.
Third, integer arithmetic is always faster than floating point.
>
in feet and inches 'int' has been used as the result
would have been a floating value. so casting as been
used. But doesnt that complicate things?The results are cast back to an int because it would look silly and meaningless to print a result of, for instance, 5.00000001 feet, 8.00045 inches.
cant one just
use long for all variables and forgot about worrying
whether the value will fit or not. No. You should never disregard whether the results of arithmetic operations will overflow the size of the word you are using. Even though a long type can contain a pretty huge number, you can still easily overflow it and get nonsensical results.
Also, a 32 bit word is the native size for most of the machines most of us use. This means that arithmetic operations are fastest on int types (for most of us). This shouldn't be a primary design consideration but it should be taken into account. -
I want to change my credit card payment but when I signed in,the itunes always said "This apple ID has not yet been used int the itunes store." And when i clicked the review button, the create apple id appears. Can someone pls help me? Thanks.
FAQ apple id http://support.apple.com/kb/HT5622?viewlocale=en_US
http://support.apple.com/kb/HT1311 -
Using ints or floats for Color
Thanks in advance for taking time to read this message.
I am using "Color" and need the most accurate color rendering. I found that I was losing some accuracy with Color(int, int, int), with integers ranging from 0-255. Because of this loss of accuracy, I am contemplating using Color(float, float, float) to make my colors. The float values can range from 0 - 1.
"Theoretically" using integers one can effectively create 256^3 colors. How many colors can be created when using floats? More importantly, how do the float produced colors correspond to the more widely used int colors?
Thanks,
Every_manAssuming you want a RGB color scheme, you could get approx (2^22)^3 different colors, since a float has 2^22 bits for the mantissa (assuming you want an even spread between 0 and 1).
When using Color(float, float, float) Java will try to map these values to the available system as best as possible. Therefore if your system can hadle more than 256 values for each of the RGB values you should get better color resolution.
If you system does not use RGB encoding, you should probably use Color(ColorSpace, float[], float) -
I've designed Calculator Program, used by String function
Hello Everyone,
I've designed Calculator Program, used by String function. U've any Feedback in this program, cantact me.
Thanks & Regards,
SABARI SARAVANAN M
Certified LabVIEW Associate Developer
Attachments:
calculator.vi 71 KBHi Jitendra,
Does the dump log shows that the cause is memory shortage?
Thanks and Best Regards,
Vikas Bittera.
**Points for useful answers** -
For school I am working on an app using C# in visual studio that allows a student to enter their name, the number of points they earned and the points possible. When they click a submit button, the grade percentage is calculated in a hidden field and then
the percentage and letter grade should spit out into the gridview. THe issue I am having is trying to figure out how to translate within the if statements regarding the percentage amount equalling whatever letter grade, and then spit that letter grade out
into the gridview. Here is the code I have so far:
protected void btnSubmit_Click(object sender, EventArgs e)
SqlStudent.Insert();
hdnGradePercent.Value = (((int.Parse("txtPointsEarned.Text")) / (int.Parse("txt.PointsPoss.Text")) * 100)).ToString();
if ((int.Parse(hdnGradePercent.Value) >= 0) & ((int.Parse(hdnGradePercent.Value) <= 59)))
(this is where I am having trouble. I can't figure out how to get the letter grade and percent to spit out into the gridview.)
else if ((int.Parse(hdnGradePercent.Value) >= 60) & ((int.Parse(hdnGradePercent.Value) <= 69)))
else if ((int.Parse(hdnGradePercent.Value) >= 70) & ((int.Parse(hdnGradePercent.Value) <= 79)))
else if ((int.Parse(hdnGradePercent.Value) >= 80) & ((int.Parse(hdnGradePercent.Value) <= 89)))
else if ((int.Parse(hdnGradePercent.Value) >= 90) & ((int.Parse(hdnGradePercent.Value) <= 100)))
Any help would be greatly appreciated! I've been stuck on this for hours and I"m losing my mind!!Please post ASP.NET questions in the ASP.NET forums (http://forums.asp.net ).
-
I need help with this program ( Calculating Pi using random numbers)
hi
please understand that I am not trying to ask anymore to do this hw for me. I am new to java and working on the assignment. below is the specification of this program:
Calculate PI using Random Numbers
In geometry the ratio of the circumference of a circle to its diameter is known as �. The value of � can be estimated from an infinite series of the form:
� / 4 = 1 - (1/3) + (1/5) - (1/7) + (1/9) - (1/11) + ...
There is another novel approach to calculate �. Imagine that you have a dart board that is 2 units square. It inscribes a circle of unit radius. The center of the circle coincides with the center of the square. Now imagine that you throw darts at that dart board randomly. Then the ratio of the number of darts that fall within the circle to the total number of darts thrown is the same as the ratio of the area of the circle to the area of the square dart board. The area of a circle with unit radius is just � square unit. The area of the dart board is 4 square units. The ratio of the area of the circle to the area of the square is � / 4.
To simuluate the throwing of darts we will use a random number generator. The Math class has a random() method that can be used. This method returns random numbers between 0.0 (inclusive) to 1.0 (exclusive). There is an even better random number generator that is provided the Random class. We will first create a Random object called randomGen. This random number generator needs a seed to get started. We will read the time from the System clock and use that as our seed.
Random randomGen = new Random ( System.currentTimeMillis() );
Imagine that the square dart board has a coordinate system attached to it. The upper right corner has coordinates ( 1.0, 1.0) and the lower left corner has coordinates ( -1.0, -1.0 ). It has sides that are 2 units long and its center (as well as the center of the inscribed circle) is at the origin.
A random point inside the dart board can be specified by its x and y coordinates. These values are generated using the random number generator. There is a method nextDouble() that will return a double between 0.0 (inclusive) and 1.0 (exclusive). But we need random numbers between -1.0 and +1.0. The way we achieve that is:
double xPos = (randomGen.nextDouble()) * 2 - 1.0;
double yPos = (randomGen.nextDouble()) * 2 - 1.0;
To determine if a point is inside the circle its distance from the center of the circle must be less than the radius of the circle. The distance of a point with coordinates ( xPos, yPos ) from the center is Math.sqrt ( xPos * xPos + yPos * yPos ). The radius of the circle is 1 unit.
The class that you will be writing will be called CalculatePI. It will have the following structure:
import java.util.*;
public class CalculatePI
public static boolean isInside ( double xPos, double yPos )
public static double computePI ( int numThrows )
public static void main ( String[] args )
In your method main() you want to experiment and see if the accuracy of PI increases with the number of throws on the dartboard. You will compare your result with the value given by Math.PI. The quantity Difference in the output is your calculated value of PI minus Math.PI. Use the following number of throws to run your experiment - 100, 1000, 10,000, and 100,000. You will call the method computePI() with these numbers as input parameters. Your output will be of the following form:
Computation of PI using Random Numbers
Number of throws = 100, Computed PI = ..., Difference = ...
Number of throws = 1000, Computed PI = ..., Difference = ...
Number of throws = 10000, Computed PI = ..., Difference = ...
Number of throws = 100000, Computed PI = ..., Difference = ...
* Difference = Computed PI - Math.PI
In the method computePI() you will simulate the throw of a dart by generating random numbers for the x and y coordinates. You will call the method isInside() to determine if the point is inside the circle or not. This you will do as many times as specified by the number of throws. You will keep a count of the number of times a dart landed inside the circle. That figure divided by the total number of throws is the ratio � / 4. The method computePI() will return the computed value of PI.
and below is what i have so far:
import java.util.*;
public class CalculatePI
public static boolean isInside ( double xPos, double yPos )
double distance = Math.sqrt( xPos * xPos + yPos * yPos );
public static double computePI ( int numThrows )
Random randomGen = new Random ( System.currentTimeMillis() );
double xPos = (randomGen.nextDouble()) * 2 - 1.0;
double yPos = (randomGen.nextDouble()) * 2 - 1.0;
int hits = 0;
int darts = 0;
int i = 0;
int areaSquare = 4 ;
while (i <= numThrows)
if (distance< 1)
hits = hits + 1;
if (distance <= areaSquare)
darts = darts + 1;
double PI = 4 * ( hits / darts );
i = i+1;
public static void main ( String[] args )
Scanner sc = new Scanner (System.in);
System.out.print ("Enter number of throws:");
int numThrows = sc.nextInt();
double Difference = PI - Math.PI;
System.out.println ("Number of throws = " + numThrows + ", Computed PI = " + PI + ", Difference = " + difference );
}when I tried to compile it says "cannot find variable 'distance' " in the while loop. but i thought i already declare that variable in the above method. Please give me some ideas to solve this problem and please check my program to see if there is any other mistakes.
Thanks a lot.You've declared a local variable, distance, in the method isInside(). The scope of this variable is limited to the method in which it is declared. There is no declaration for distance in computePI() and that is why the compiler gives you an error.
I won't check your entire program but I did notice that isInside() is declared to be a boolean method but doesn't return anything, let alone a boolean value. In fact, it doesn't even compute a boolean value. -
HANA, Aggregations and calculating percentages
I have a table containing user-role assignments, e.g. the table contains tuples of the form (userA, roleA), (userA, roleB). Now, I would like to get an overview on how the distribution of users across roles. I would like to get the following overview.
role
COUNT DISTINCT user
percentage
roleA
5
5/15 * 100 = 33,3 %
roleB
8
53,3 %
roleC
10
66,6 %
Total
15
Using SAP HANA Studio, I created a Calculated View and count the number of distinct users with a counter. However, how to compute the totals (note that this is not the sum of distinct users per role) and how to compute then the percentages?
Thanks!OK, totals are now computed by modeling the following two aggregations:
1. count distinct users per role
2. count distinct users in the table
Then the two aggregations are joined.
A new problem pops-up: I divide the two different counts in a calculated column or calculated attribute. Whatever I try, the result of dividing two integers is 0. What should I do?
Maybe you are looking for
-
Error while deploying DataSpace project
Hi, I have migrated an dataservice project from ALDSP2.5 to 3.0. using the upgrade tool as described on the BEA docs site. While i try to deploy this EAR file i get the following error: > <Mar 26, 2008 5:55:45 PM IST> <Warning> <Deployer> <BEA-149004
-
My Apple account password has been reset a couple times due to Apple telling me my passwords are incorrect. I know they aren't because I have already had to change the password three times, and I keep record of my password. Yet, it continuously tel
-
Not able to connect to wireless network using WEP 128 bit hex password
I'm using a 128 bit hex WEP password on a Belkin wireless router. My ascii passphrase is 13 characters. I tried using the hex password generated by the Belkin router, as well as the hex equivalent of my ascii passphrase. Every time, I am told that ei
-
Remove empty space in Picture Library Slideshow web part
I'm using Picture Library Slideshow web part in one of my pages. The web part itself is working fine, but I'm a bit annoyed by the white space the web part is consuming. The web part puts lots of empty space between the web part header and the pictur
-
Applets don't see each other when having certain jar files as archive
Hi, I have read a nice solution for Applet2Applet communication when they are on different html pages (different frames or windows) at http://www.javaworld.com/javaworld/javatips/jw-javatip101.html. They see each other through a static AppletManager.