format numbers in java to remove decimals and add decimals - java

I am looking at Java code which will perform following two operations:-
If I am sending value 10.00, my method should format it to 1000 and
If I am getting 1000 in response from 3rd party system, I need to convert 1000 to 10.00 in my another method. Simply whatever decimal value (2 digit's after decimal) I'm sending need to remove decimals and whatever Non-decimal Value I'm receiving need to convert to decimals (2 digits after decimals)
I tried to write the code but it's not working expected. Can anyone please guide me? I'm using JDK 7.

You were supposed to provide your own code which doesn't work, so we can help you figure it out and make it work, not posting a problem and let us do all the work.
Input string and convert it to char array with toCharArray() method. Rewrite the array without the dot for the first part. For the second part do the same thing except you insert dot on position you want.
BTW your question is not clear enough, how does the algorithm work, what happens if you get number 15, or 1555...does it translate to 0.15 and 15.55?

Related

Jackson JSON conversion rounds values outside of integer range (2^32) [duplicate]

I need to parse a json that contains a long number (that was produces in a java servlet). The problem is the long number gets rounded.
When this code is executed:
var s = '{"x":6855337641038665531}';
var obj = JSON.parse(s);
alert (obj.x);
the output is:
6855337641038666000
see an example here: http://jsfiddle.net/huqUh/
why is that, and how can I solve it?
As others have stated, this is because the number is too big. However, you can work around this limitation by sending the number as a string like so:
var s = '{"x":"6855337641038665531"}';
Then instead of using JSON.parse(), you can use a library such as javascript-bignum to work with the number.
It's too big of a number. JavaScript uses double-precision floats for numbers, and they have about 15 digits of precision (in base 10). The highest integer that JavaScript can reliably save is something like 251.
The solution is to use reasonable numbers. There is no real way to handle such large numbers.
The largest number JavaScript can handle without loss of precision is 9007199254740992.
I faced this issue some time ago, I was able to solve using this lib: https://github.com/josdejong/lossless-json
You can check this example:
let text = '{"normal":2.3,"long":123456789012345678901,"big":2.3e+500}';
// JSON.parse will lose some digits and a whole number:
console.log(JSON.stringify(JSON.parse(text)));
// '{"normal":2.3,"long":123456789012345680000,"big":null}' WHOOPS!!!
// LosslessJSON.parse will preserve big numbers:
console.log(LosslessJSON.stringify(LosslessJSON.parse(text)));
// '{"normal":2.3,"long":123456789012345678901,"big":2.3e+500}'

How to calculate any power of a base 2 number in Java by not using BigInteger?

How can I calculate in Java any power of a number in a base 2 (2^n, where n can be any number), without using the BigInteger class?
Let's say I got the binary number 100000000000000000000100000000001 stored in a given array, and I want to print its value in a decimal number (just to print it, let's say we store it in a String type).
I'm not sure I understand your problem completely, but if n is the binary number converted to a decimal number, then you are playing with way too large numbers.
Consider the binary number as decimal. Your example would be the decimal number 4294969345. Just try to consider what 2^4294969345 would be. As an example 2^429 would be 1.38633485×10^129. There's no way you can execute this.
I agree with the others, please share your code, and maybe you can get a better answer.
EDIT: If it's just a conversion from the big binary number to a decimalnumber, you can use Long.parseLong(binaryNumber, 2), where binaryNumber is your binary number as a String.
The values needs to be saved somewhere to be "just printed", whether a data structure or a primitive, in your case it's way too large for an integer ( > 2^31), you can use long instead (Long.parseLong(binary, 2)) but eventually if it keeps getting bigger, you will need another way, either using BigInteger or your own brains.

Why pattern "33333.##" acts so strange when we use the DecimalFormat method .format()?

Yesterday I tried to explore by myself the behavior of DecimalFormat method .format() with all its placeholders and what they do.
So I wrote two numbers and tried different patterns on them. With "#.##" all non-significant zeros were cut and with "0000.00" the method added leading zeros in front of the number. That was OK, but then I tried some strange patterns just to see what would happen.
With pattern "33333.##" the final output was really strange. You could see my code below:
DecimalFormat df = new DecimalFormat("33332.##");
double a= 222.46705219;
double b=-102.000;
System.out.println(df.format(a));
System.out.println(df.format(b));
And its output was:
33332222,47
-33332102,0
Same input as numbers but with used pattern "33033.##" gave result:
33222,4732
33102
I understand that the program added the formatted number in the place of 0 but why when zero is not presented as placeholder, the method still rounds the first and (obviously) the second number? Why my first number was rounded to its second digit as it has to be, but the second number (b) was printed with a zero at the end? And why when the 0-placeholder is presented in the middle of "33033.##" the program inserts formatted number a on its place but doesn't print "33" at the end of number b?
I really don't know how to explain this behavior.
The documentation highlights a clear syntax for the pattern you should be setting. Both of your formats go against the required syntax, and so your findings should not be seen as reliable, and may change in future versions. Frankly, I'm surprised that the constructor doesn't throw an exception at these formats.
33332.##: The 33332 is seen as a prefix, and the remainder, .##, is not valid as either a 0 or a # is required before the decimal point.
33033.##: The 33 is seen as a prefix, leaving 033.##. Given that 0, . nor # cannot be part of any prefix or suffix, and 3 can only be part of a prefix or suffix, this pattern is invalid.

Java - unexpected result when rounding a double/float to 2 decimals

I encounter a problem when round a double to 2 decimals. I know this questions have been asked in many places. But my question is slightly different and I cannot find it in other places.
So far as I know, there are 2 ways to do this.
Math.round(double*100.0)/100.0
DecimalFormat(“###.##”)
I am trying to use the first way: a custom way to round double.
When the second decimal is 0, the result will only print the first decimal and ignore the second one.
For example,
Math.round(1.23333*100.0)/100.0 The result is 1.23. This works good.
Math.round(3.90*100.0)/100.0. The result is 3.9. Problem occurs. I want to show 3.90 instead of 3.9
Math.round(3*100.0)/100.0. The result is 4.0. I want 4.00 instead of 4.0
So, my question is that how I can have a double value with 2 decimals no matter if the last decimal is 0 or not. I know I can use the second way- DecimalFormat(“###.##”) to achieve what I want! But is it possible to do it by using the first way?
Edit: Thanks for the answers. It looks like it is NOT possible to use the round() method to achieve it. However, some people suggest to use the combination of 2 ways to achieve it. But I think using only DecimalFormat(“###.##”) can get what I want. Can anyone confirm it?
I would suggest using String.format("%1$.2f",x). It rounds the value to the specified precision (2 digits in our example) and leaves the trailing zeros on the right.
System.out.println(String.format("%1$.2f",3.121)) gives 3.12
System.out.println(String.format("%1$.2f",3.129)) gives 3.13
System.out.println(String.format("%1$.2f",3.12)) gives 3.12
System.out.println(String.format("%1$.2f",3.10)) gives 3.10
Have you tried the following?
DecimalFormat(“###.00”)
If not mistaken, trailing zeros are left blank when using the #-sign.
I believe you need to use a combination of both to achieve your needs.
The rounding to obtain a number with two decimals, and the DecimalFormat to display it with two decimals.
You should be formatting your result with DecimalFormat
DecimalFormat format = new DecimalFormat("0.00");
System.out.println(Math.round(3.90*100.0)/100.0); // 3.9
System.out.println(format.format(Math.round(3.90*100.0)/100.0)); // after using format 3.90
System.out.println(format.format(Math.round(3*100.0)/100.0));
And the output is
3.9
3.90
3.00

String.format() and hex numbers in Java

I'm trying to figure out why String.format() is behaving the way it does.
Context: Systems programming class, writing an assembler.
There is a 5 character hex field in the object file, which I am creating from a value.
Tried using: String.format("%05X", decInt);
This works as intended for positive numbers
(11 -> 0000B)
However it fails for negative numbers
(-1 -> FFFFFFFF instead of FFFFF)
I suppose I could just take a substring of the last 5 characters, but I would still like to figure out why it behaves this way.
The width used in format is always a minimum width. In this case, instead of using sub string operations I would suggest:
String.format("%05X", decInt & 0xFFFFF);
Format width only works to create a minimum number of digits, and only has effect on leading zeroes.
Instead of substring, you could use a bit mask:
String.format("%05X", decInt & 0x0FFFFF)
By the way, 11 -> 0000B, not 0000A as claimed in your question.

Categories