This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 2 years ago.
What do I do if I want to divide only tens? for example I have 16 when I divide it to 10 it will only answer 1 if I do 23 it will give me 2, like what I want to do is like diving 20(example) and 10 and it is ignoring the 6 in 26.
Integer values ignore decimal places in division:
int num = 236;
int div = num / 10;
int remainder = num % 10;
System.out.println("div = " + div);
System.out.println("remainder = " + remainder);
You can however use float or double instead though to get those decimal placed and then optionally round the result back to an integer.
double withDecimal = (double) num / 10.0;
int rounded = (int) Math.round(withDecimal);
System.out.println("withDecimal = " + withDecimal);
System.out.println("rounded = " + rounded);
Integer division in Java truncates decimals (hence the name). In order to maintain the decimals you have to make at least one of the variables a double or float like so:
double x = 16 / 10.0; //1.6
double y = 23 / 10.0; //2.3
Step 1: get the reminder by using number % 10;
Step 2: substract the reminder from the original number and store the result in a variable
Step 3: now divide the new number by 10.
public static void main(String []args){
int number = 33;
int reminder = number % 10;
number = number - reminder;
System.out.println(number / 10);
}
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have a task to add each numbers. One of my colleague helped me out and here's the code.
public class Solution {
public static void main(String[] args) {
System.out.println(sumDigitsInNumber(546));
}
public static int sumDigitsInNumber(int number) {
int sum = 0;
sum = sum + number%10;
number = number/10;
sum = sum + number%10;
number = number/10;
sum = sum + number%10;
number = number/10;
return sum;//write your code here
}
I'm not sure exactly how this works. Can someone please explain to me? Thanks.
You can use within while the loop which will accept any number as #GBlodgett suggested
public static void main(String[] args) {
System.out.println(sumDigitsInNumber(546));
}
public static int sumDigitsInNumber(int number) {
int sum = 0;
while(number!=0)
{
sum = sum + number%10;
number = number/10;
}
return sum;//write your code here
}
In Java % is the modulo operator. It delivers the remainder of that division. If you divide integer values in Java, any remainder will be lost.
If you add some makeshift logging like that:
public static int sumDigitsInNumber(int number) {
int sum = 0;
sum = sum + number % 10;
number = number / 10;
System.out.println(number);
sum = sum + number % 10;
number = number / 10;
System.out.println(number);
sum = sum + number % 10;
number = number / 10;
System.out.println(number);
return sum; // write your code here
you will get the following output:
54
5
0
15
546 % 10 = 6
546 / 10 = 54
54 % 10 = 4
54 / 10 = 5
5 % 10 = 5
5 / 10 = 0
sum = 6 + 5 + 4 = 15
Your code will only work up to three digits. If you transfer the sequence of modulo and division operations into a loop it will be a generic solution.
The JVM(Java Virtual Machine) starts executing your code and public static void
main(String[] args) is the starting point.
Then executes System.out.println(sumDigitsInNumber(546));
System.out.println() is a method that prints the argument passed, into the System.out which is generally stdout (Standard output). The argument passed is the sumDigitsInNumber(546) method, hence it would print what sumDigitsInNumber() would return.
sumDigitsInNumber() initializes a sum variable with 0 to store the sum of 546.
sum = sum + number%10 gives you 6 (0 + 6), where number%10 gives
the last digit of 546 which is 6
number = number / 10 will replace number by 54 because 546/10 is 54.6 since it is an integer division .6 is ignored and 54 is stored in the number.
Repeat the above step twice but the number being 54 and then 5.
return sum returns the sum to the caller which is your main() method, hence System.out.println() printing the sum of 546.
Step by step:
this creates variable named sum and assigns it value of 0:
int sum = 0;
this does the following:
it assigns to variable 'sum' the result of sum + number % 10 (where a number is an argument passed to the method)
sum = sum + number%10;
number % 10 is in your example a remainder of 456 / 10, so in 456, you can pack number 10 exactly 45 times, whatever is left that is less then 10 is your result (remainder), in this case 6.
see http://www.cafeaulait.org/course/week2/15.html
next we divide current number by 10:
number = number / 10;
so 456 / 10 = 45.6
and as the type of variable is int - it is actually 45 (as int always rounds down the remainder) - see Int division: Why is the result of 1/3 == 0?
then it is being repeated 2 times until all 3 digits are summed up.
Notice, that your method will only work for 3 digit numbers. That's not that good.
You can easily make your method to work with any digits length int number passed.
Hint: use loops!
As you can see, you're repeating the same piece of code 3 times.
You could place it inside a loop and make it execute as many times as there are digits in your number.
something along these lines, but you need to figure out when to stop the while loop!
int sum = 0;
while (?WHEN TO EXIT?) {
sum = sum + number % 10;
number = number / 10;
}
Think about when you can exit loop (when, in example, maybe this number variable that you divide by 10 each iteration can tell you that all digits have been processed?)
Here is a solution that computes the sum of a number, no matter how many digits it has:
Generally speaking, a number has exactly [log(number)+1] digits, the tempInt variable is introduced to store the parameter value, it is considered a bad practice to modify the values of the method parameters :
public static int sumOfDigits(int number) {
int sum = 0;
int length = (int) Math.ceil(Math.log10(number));
int tempInt = number;
for (int i = 0; i < length; i++) {
sum += tempInt % 10;
tempInt /= 10;
}
return sum;
}
public class Solution {
public static void main(String[] args) {
System.out.println(sumDigitsInNumber(546));
}
public static int sumDigitsInNumber(int number) {
int sum = 0;
sum = sum + number%10; // number%10 = the last digit of 546 (= 6), sum = 0 + 6
number = number/10; // number = number whithout the last digit (54)
sum = sum + number%10; // number%10 = the last digit of 54 (= 4), sum = 0 + 6 + 4
number = number/10; // number = number whithout the last digit (5)
sum = sum + number%10; // number%10= the last digit of 5 (= 5), sum = 0 + 6 + 4 + 5
number = number/10; // number = number whithout the last digit (useless)
return sum;//sum = 6 + 5 + 4 = 15
}
I am generating random numbers and I am having a equal distribution issue. The first and last numbers in the range always have half the change of getting chosen because they don't have that possibility of being rounded to on both sides.
For example, if the user chooses a min of 1 and a max of 10, 1 and 10 will have a decreased chance of getting picked compared to the others.
Here is my current code:
double num = random.nextDouble() * (max - min) + min;
String finalNum = String.format("%." + precision + "f", num);
I know I could fix this by using a nextInt() instead but the problem is that I want to keep it a double because the user selects how many decimal places there will be.
Help is appreciated.
double min = 1.0;
double max = 10.0;
double rand = r.nextDouble();
//now we add 1 for the spread (we want the number to be from 0.5 to 10.5)
double range = max - min + 1;
rand *=range;
//now we shift by an offset of min-0.5;
rand += (min -0.5);
//now we round the number
int intRand = Math.round(rand);
you can use rand (double) for displaying your precision
and use intRand (int) for your integer random.
This question already has answers here:
How to merge two int(s) into a double in JAVA?
(6 answers)
Closed 6 years ago.
Is there a way to force a number to be placed behind the decimal mark of a number?
Say I have a number = 2, and another number = 23. Is there a way for me to force 23 into 0.23, so that when I add the numbers I end up with 2.23? And is there a way to do this when the number of digits in the second number, in this case 23, are unknown?
EDIT:
I realize this was badly written. I am currently working on a program that converts from imperial units to metric units. Part of the code looks like this:
double feet = nextDouble();
double inches = nextDouble();
double heightInMeters = (feet + (inches/10)) / 3.2808;
The problem with this code is that I anticipate that the user only enters a value <0, 9> for feet. Is there a way to force the input for inches to something like 0.x where x = inches so that it doesn't matter if the number is greater than 9?
Would be lovely if it was possible without using toString() and parseInt().
You can get the number of digits in an integer, i, using:
1 + Math.floor(Math.log10(i))
(not ceil(log10(i)), since that calculates that 1 has zero digits)
You then need to divide i by 10 to the power of that number:
i / Math.pow(10, 1 + Math.floor(Math.log10(i)))
e.g.
23 / Math.pow(10, 1 + Math.floor(Math.log10(23))) == 0.23
Ideone demo
Alternatively, if you think those floating point operations log and pow are too expensive, you can determine the number of digits with a loop:
int d = 1;
while (d < i) d *= 10;
then
System.out.println(i / (double) d);
(noting that you need to cast at least one of the numerator or denominator to a floating point type, otherwise it will use integer division).
Try parsing to double like this, from a string:
Option 1
try
{
int n = 2;
int decimal = 23;
String full = Integer.toString(n) + '.' + Integer.toString(decimal);
double val = Double.parseDouble(full);
} catch (Exception e) //Or whatever exception
{
//Code
}
Option 2
Of course, there are simpler methods, like this:
try
{
int n = 2;
int decimal = 23;
double val = Double.parseDouble(n + "." + decimal);
} catch (Exception e) //Or whatever exception
{
//Code
}
I personally would recommend the solution directly above, since it is the simplest, and requires the least code.
Live Example for Second Option
Simple implementation using Strings:
public class Mainclass {
public static void main(String[] args) {
Integer num = 1546;
Integer num2 = 2;
String s = num.toString();
s = "0." + s;
Double d = Double.parseDouble(s);
System.out.println(num2+d ); // 2.1546
}
}
This question already has answers here:
Fahrenheit to Celsius conversion yields only 0.0 and -0.0
(5 answers)
Closed 8 years ago.
It returns 0 if performed with plain BODMAS operation.
I have something like this:
int mbUsed=1;
int mbTotal=25;
int percent=(mbUsed/mbTotal)*100;
1/25 will return 0, since int division can't return fractions.
You can cast to double for floating point division :
int percent=(int) ((double)mbUsed/mbTotal)*100;
Or if you want a more accurate result :
double percent = ((double)mbUsed/mbTotal)*100;
If you want to stay with int division, you can change the order of the operators :
int percent = (100*mbUsed)/mbTotal;
The int data type in Java contains whole values. You should instead store your values in the double or float data types, as they can contain decimal points.
Here you can see an example:
public static void main(String[] args) {
int iVal1 = 1;
int iVal2 = 25;
int iVal3 = iVal1 / iVal2;
System.out.println("Integer storage, int variables: " + iVal3);
double dVal1 = iVal1 / iVal2;
System.out.println("Double storage, int variables: " + dVal1);
double dVal2 = (double) iVal1 / (double) iVal2;
System.out.println("Double storage, double variables: " + dVal2);
}
Which outputs:
Integer storage, int variables: 0
Double storage, int variables: 0.0
Double storage, double variables: 0.04
Notice how the values you are dividing also have to have at least double precision. In my example I simply type cast them to a double (seeing as they are whole numbers, it will make no difference), but you could also store them in double data types as well.
You can also use BigDecimal, so for other ratio's You can manipulate scale:
http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html
This is especially recommended for currencies.
BigDecimal dividend= BigDecimal.ONE;
BigDecimal divisor = new BigDecimal(25);
BigDecimal result = dividend.divide(divisor );
You might also consider just using doubles for your values mbUsed and mbTotal.
Example:
double mbUsed = 1;
double mbTotal = 25;
double percent = (mbUsed * 100)/mbTotal;
You could even add a decimal format, in case the numbers for mbUsed and mbTotal change.
Example:
DecimalFormat df = new DecimalFormat("#.00");
Then, you can use df.format(percent) in a System.out.println statement to display the percentage rounded to two decimal points.
Here is an example of some code that compiles as it should:
double mbUsed = 1;
double mbTotal = 25;
double percent = (mbUsed * 100)/mbTotal;
DecimalFormat df = new DecimalFormat("#.00");
System.out.println("The number used: " + df.format(mbUsed));
System.out.println("The total number: " + df.format(mbTotal));
System.out.println("The percentage used is: " + df.format(percent) + "%.");
This outputs:
The number used: 1.00
The total number: 25.00
The percentage used is: 4.00%
I hope this works well for you!
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
Is there a library that will convert a Double to a String with the whole number, followed by a fraction?
For example
1.125 = 1 1/8
I am only looking for fractions to a 64th of an inch.
Your problem is pretty simple, because you're assured the denominator will always divide 64. in C# (someone feel free to translate a Java version):
string ToMixedFraction(decimal x)
{
int whole = (int) x;
int denominator = 64;
int numerator = (int)( (x - whole) * denominator );
if (numerator == 0)
{
return whole.ToString();
}
while ( numerator % 2 == 0 ) // simplify fraction
{
numerator /= 2;
denominator /=2;
}
return string.Format("{0} {1}/{2}", whole, numerator, denominator);
}
Bonus: Code Golf
public static string ToMixedFraction(decimal x) {
int w = (int)x,
n = (int)(x * 64) % 64,
a = n & -n;
return w + (n == 0 ? "" : " " + n / a + "/" + 64 / a);
}
One problem you might run into is that not all fractional values can be represented by doubles. Even some values that look simple, like 0.1. Now on with the pseudocode algorithm. You would probably be best off determining the number of 64ths of an inch, but dividing the decimal portion by 0.015625. After that, you can reduce your fraction to the lowest common denominator. However, since you state inches, you may not want to use the smallest common denominator, but rather only values for which inches are usually represented, 2,4,8,16,32,64.
One thing to point out however, is that since you are using inches, if the values are all proper fractions of an inch, with a denominator of 2,4,8,16,32,64 then the value should never contain floating point errors, because the denominator is always a power of 2. However if your dataset had a value of .1 inch in there, then you would start to run into problems.
How about org.apache.commons.math ? They have a Fraction class that takes a double.
http://commons.apache.org/math/api-1.2/org/apache/commons/math/fraction/Fraction.html
You should be able to extend it and give it functionality for the 64th. And you can also add a toString that will easily print out the whole number part of the fraction for you.
Fraction(double value, int
maxDenominator) Create a fraction
given the double value and maximum
denominator.
I don't necessarily agree, base on the fact that Milhous wants to cover inches up to 1/64"
Suppose that the program demands 1/64" precision at all times, that should take up 6 bits of the mantissa. In a float, there's 24-6 = 18, which (if my math is right), should mean that he's got a range of +/- 262144 + 63/64"
That might be enough precision in the float to convert properly into the faction without loss.
And since most people working on inches uses denominator of powers of 2, it should be fine.
But back to the original question, I don't know any libraries that would do that.
Function for this in a C-variant called LPC follows. Some notes:
Addition to input value at beginning is to try to cope with precision issues that otherwise love to wind up telling you that 5 is 4 999999/1000000.
The to_int() function truncates to integer.
Language has a to_string() that will turn some floats into exponential notation.
string strfrac(float frac) {
int main = to_int(frac + frac / 1000000.0);
string out = to_string(main);
float rem = frac - to_float(main);
string rep;
if(rem > 0 && (to_int(rep = to_string(rem)) || member(rep, 'e') == Null)) {
int array primes = ({ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47 });
string base;
int exp;
int num;
int div;
if(sscanf(rep, "%se%d", base, exp) == 2) {
num = to_int(replace(base, ".", ""));
div = to_int(pow(10, abs(exp)));
} else {
rep = rep[2..];
num = to_int(rep);
div = to_int(pow(10, strlen(rep)));
}
foreach(int prime : primes) {
if(prime > num)
break;
while((num / prime) * prime == num && (div / prime) * prime == div) {
num /= prime;
div /= prime;
}
}
out += " " + num + "/" + div;
}
return out;
}
i wrote this for my project i hope it could be usefull:
//How to "Convert" double to fraction("a/b") - kevinlopez#unitec.edu
private boolean isInt(double number){
if(number%2==0 ||(number+1)%2==0){
return true;
}
return false;
}
private String doubleToFraction(double doub){
//we get the whole part
int whole = (int)doub;
//we get the rest
double rest = doub - (double)whole;
int numerator=1,denominator=1;
//if the whole part of the number is greater than 0
//we'll try to transform the rest of the number to an Integer
//by multiplying the number until it become an integer
if(whole >=1){
for(int i = 2; ; i++){
/*when we find the "Integer" number(it'll be the numerator)
* we also found the denominator(i,which is the number that transforms the number to integer)
* For example if we have the number = 2.5 when it is multiplied by 2
* now it's 5 and it's integer, now we have the numerator(the number (2.5)*i(2) = 5)
* and the denominator i = 2
*/
if(isInt(rest*(double)i)){
numerator = (int)(rest*(double)i);
denominator = i;
break;
}
if(i>10000){
//if i is greater than 10000 it's posible that the number is irrational
//and it can't be represented as a fractional number
return doub+"";
}
}
//if we have the number 3.5 the whole part is 3 then we have the rest represented in fraction 0.5 = 1/2
//so we have a mixed fraction 3+1/2 = 7/2
numerator = (whole*denominator)+numerator;
}else{
//If not we'll try to transform the original number to an integer
//with the same process
for(int i = 2; ; i++){
if(isInt(doub*(double)i)){
numerator = (int)(doub*(double)i);
denominator = i;
break;
}
if(i>10000){
return doub+"";
}
}
}
return numerator+"/"+denominator;
}
My code looks like this.
public static int gcd(int a, int b)
{
if (b == 0)
return a;
else
return gcd(b, a % b);
}
public static String doubleToStringFraction(Double d)
{
StringBuffer result = new StringBuffer(" " + ((int) Math.floor(d)));
int whole = (int) ((d - Math.floor(d)) * 10000);
int gcd = gcd(whole, 10000);
result.append(" " + (whole / gcd) + "/" + 10000 / gcd + " ");
return result.toString();
}
As several others have poited out, fractions of 64 can be precicely represented by IEEE-floats. This means we can also convert to a fraction by moving and masking bits.
This is not the place to explain all details of floating point representations, please refer to wikipedia for details.
Briefly: a floating point number is stored as (sign)(exp)(frac) where sign is 1 bit, exp is 11 bits and frac is the fraction part (after 1.) and is 52 bits. This is enterpreted as the number:
(sign == 1 ? -1 : 1) * 1.(frac) * 2^(exp-1023)
Thus, we can get the 64th by moving the point accoring to the exponent and masking out the 6 bits after the point. In Java:
private static final long MANTISSA_FRAC_BITMAP = 0xfffffffffffffl;
private static final long MANTISSA_IMPLICIT_PREFIX = 0x10000000000000l;
private static final long DENOM_BITMAP = 0x3f; // 1/64
private static final long DENOM_LEN = 6;
private static final int FRAC_LEN = 52;
public String floatAsFrac64(double d) {
long bitmap = Double.doubleToLongBits(d);
long mantissa = bitmap & MANTISSA_FRAC_BITMAP | MANTISSA_IMPLICIT_PREFIX;
long exponent = ((bitmap >> FRAC_LEN) & 0x7ff) - 1023;
boolean negative = (bitmap & (1l << 63)) > 0;
// algorithm:
// d is stored as SE(11)F(52), implicit "1." before F
// move point to the right <exponent> bits to the right:
if(exponent > FRAC_LEN) System.out.println("warning: loosing precision, too high exponent");
int pointPlace = FRAC_LEN-(int)exponent;
// get the whole part as the number left of the point:
long whole = mantissa >> pointPlace;
// get the frac part as the 6 first bits right of the point:
long frac = (mantissa >> (pointPlace-DENOM_LEN)) & DENOM_BITMAP;
// if the last operation shifted 1s out to the right, we lost precision, check with
// if any of these bits are set:
if((mantissa & ((MANTISSA_FRAC_BITMAP | MANTISSA_IMPLICIT_PREFIX) >> (pointPlace - DENOM_LEN))) > 0) {
System.out.println("warning: precision of input is smaller than 1/64");
}
if(frac == 0) return String.format("%d", whole);
int denom = 64;
// test last bit, divide nom and demon by 1 if not 1
while((frac & 1) == 0) {
frac = frac >> 1;
denom = denom >> 1;
}
return String.format("%d %d/%d", whole, frac, denom);
}
(this code can probably be made shorter, but reading bit-flipping-code like this is hard enough as it is...)
I create simply Fraction library.
The library is available here: https://github.com/adamjak/Fractions
Example:
String s = "1.125";
Fraction f1 = Fraction.tryParse(s);
f1.toString(); // return 9/8
Double d = 2.58;
Fraction f2 = Fraction.createFraction(d);
f2.divide(f1).toString() // return 172/75 (2.29)
To solve this problem (in one of my projects), I took the following steps:
Built a dictionary of decimal/fraction strings.
Wrote a function to search the dictionary for the closest matching fraction depending on the "decimal" part of the number and the matching criteria.