formatting and converting in java - java

I have few small basic problems :
How to format :
int i = 456;
to give output :
""00000456"
? I've tried %08d but it's not working. Next thing is a problem with conversion and then formatting. I have side and height of triangle, let's say int's 4,7, and 7 is the height. From formula for field we know that F=1/2(a*h). So how to get F as float, with precision up to 10 places ?
float f = a*h;
works fine, but multiplying it by 0.5 gives error and by 1/2 returns 0.

Use NumberFormat class see this or that explanation, the Formatter class or String.format

How to format :
int i = 456; to give output :
"00000456"
System.out.printf("%08d", i) can do the job.

1/2 is an integer expression, it will not be automatically converted to a float.
1/2 should be one of: 1.0f/2.0f, 1.0f/2, 1/2.0f, (float)1/(float)2, (float)1/2, 1/(float)2, float-variable/float-variable, float-variable/int-variable, int-variable/float-variable, ... you get the idea

Should be %.08d instead of %08d, secondly try multiplying by 0.5f instead.

Answer was to use String.format.
String fs = String.format("%08d", this.id);
return fs;

Related

dividing floats and rounding to int in java [duplicate]

How to round up a decimal number to a whole number.
3.50 => 4
4.5 => 5
3.4 => 3
How do you do this in Java? Thanks!
With the standard rounding function? Math.round()
There's also Math.floor() and Math.ceil(), depending on what you need.
You can use
int i = Math.round(f);
long l = Math.round(d);
where f and d are of type float and double, respectively.
And if you're working with only positive numbers, you can also use int i = (int)(d + 0.5).
EDIT: if you want to round negative numbers up (towards positive infinity, such that -5.4 becomes -5, for example), you can use this as well. If you want to round to the higher magnitude (rounding -5.4 to -6), you would be well advised to use some other function put forth by another answer.
Java provides a few functions in the Math class to do this. For your case, try Math.ceil(4.5) which will return 5.
new BigDecimal(3.4);
Integer result = BigDecimal.ROUND_HALF_UP;
Or
Int i = (int)(202.22d);
Using Math.max you can do it like this:
(int) Math.max(1, (long) Math.ceil((double) (34) / 25)
This would give you 2

How to get java to produce decimal points while dividing

I'm making a basic calculator where you can plus, times, divide and minus as i was experimenting to see if it worked i noticed that instead of 5 divided by being equal to 1.25 it only displayed 1.
Here's the code i use to handle the math problems:
if (box.getSelectedItem().equals(divide)){
JOptionPane.showMessageDialog(null, Integer.parseInt(first.getText()) / Integer.parseInt(second.getText()), "Answer", -1);
main(args);
}
Is there code that displays the decimal points as well?
Since you are using Integer,it is happening.
Use Double to preserve decimals.
In your case,use
Double.parseDouble(first.getText()) / Double.parseDouble(second.getText())
Integer division will give you Integer. Try using Double or BigDecimal data type.
You need to do the casting
(double)parseInt(first.getText()) / (double)parseInt(second.getText())
Int/Int will give you an Integer. So you need to cast it to Double to get the result in decimal.
EDIT:
If you dont want to show decimal when the result is a whole number then you need to check it like this:
Double res = (double)parseInt(first.getText()) / (double)parseInt(second.getText())
Integer x;
if(res % 1 == 0)
{
x = (int)res
}

Get the hundredths place value digit in a double variable using java

I am trying to get the digit in the hundredth's place of a double value (second digit after the decimal).
So, for example, if the double value is 48.4569999, I want to get the value 5 using any Math or BigDecimal methods, which is the hundredth's place after decimal.
I have tried the following code:
BigDecimal src = new BigDecimal("48.4569999");
BigDecimal a = src.remainder(BigDecimal.ONE);
System.out.println("a : " + a);
which results in .456999 but I dont want to use any String functions to get to the second digit. Is there any Math or Bigdecimal function to do this please ? Your help is appreciated.
Why not multiply by 100, to push your desired value to the right place, cast to int (to remove anything < 1) and then do % 10, which will give you the remainder (which will be your desired digit).
You may be looking for movePointRight(int).
int a = src.movePointRight(2).remainder(BigDecimal.TEN).intValue();
prints
a : 5

BigDecimal to String in java?

My code is:
x=new BigDecimal(x.toString()+" "+(new BigDecimal(10).pow(1200)).toString());
I am trying to concat two bigdecimals after converting them to string and then convert them back to bigdecimal.I am doing so because x has a value with a decimal point and multiplying will change its value.It compiles fine but throws a numberformat exception on execution.
My idea was to use the BigDecimal("String x") constructor to convert the string back to BigDecimal.
Note:
(for example)
x=1333.212
and I am converting it to
x=1333.2120000
It's failing to parse because you've got a space in there for no particular reason. Look at the string it's trying to parse, and you'll see it's not a valid number.
If you're just trying to add extra trailing zeroes (your question is very unclear), you should change the scale instead:
x = x.setScale(x.scale() + 1200);
Simple example:
BigDecimal x = new BigDecimal("123.45");
x = x.setScale(x.scale() + 5);
System.out.println(x); // 123.4500000
If you were trying to multiply the value by a power of 10 (as your initial question suggested), there's a much simpler way of doing this, using movePointRight:
x = x.movePointRight(1200);
From the docs:
The BigDecimal returned by this call has value (this × 10n) and scale max(this.scale()-n, 0).
You need to try in this way
BigDecimal result=new
BigDecimal("1333.212123232432543534324243253563453423423242452543535")
.multiply(new BigDecimal("10").pow(1200));
System.out.println(result);
For your Edit:
BigDecimal result=new
BigDecimal("1333.212123232432543534324243253563453423423242452543535")
.multiply(new BigDecimal("10").pow(1200));
System.out.println(result.movePointRight(-1200));

Why double width = 50/110000; the output is 0.000000000000000?

This is my code :
double width = 50/110000;
System.out.println("width ori is "+width );
And the output is: 0.00000000000
What's wrong ? the expected output has to be 4.5454545454545455E-4
Any body can explain to me why?
Because you're dividing two integers, so it will only take the integer part (integer division).
Dividing integers in a computer program requires special care. Some
programming languages, treat integer division (i.e by giving the integer quotient as the answer). So the answer is an integer.
Examples :
In real life In Java
4/3 = 1.33333 4/3 = 1
25/12 = 2.083333 25/12 = 2
9/2 = 4.5 9/2 = 4
50/110000 = 0.000454545 50/110000 = 0
You can cast one of the number (or both but it's actually useless) to double to avoid that :
double width = (double)50/110000;
double width = 50d/110000;
double width = 50.0/110000;
Result of int/int returns you an integer.
So the decimal part got truncated resulting you with an integer
You need to cast:
double width = (double)50/110000;
As #Josh M has pointed, You can also try :
double width = 50d / 110000d;
Explanation to what's happening:
In Java, the default type of numbers is int, so when you write 50/110000, they're both considered int, although you defined the result to be double.
When int division occurs, the result will be 0, because they are both ints, then the double will hold this value, which will be represented as double, so you're getting 0.000000.
Possible solutions:
Coding these numbers with d: 50d/110000d.
Casting one side explicitly (the other will be implicitly cast): (double)50/110000.
50.0/110000.
See Chapter 5. Conversions and Promotions, it'll really help you.

Categories