In Java, I have a big decimal number , I want to multiply with -1.
BigDecimal amount, total;
total = amount*-1;
If i give like this, it is throwing error upfront. How can I multiply -1 with bigdecimal number.
When you work with BigDecimals you need to work with the class functions.
BigDecimal total, minus;
total = new BigDecimal(1);
minus = new BigDecimal(-1);
System.out.println(total);
System.out.println(total.multiply(minus));
But to keep it very simple you can just use a function for this:
BigDecimal total;
total = new BigDecimal(1);
System.out.println(total.negate());
For more details check this link:
http://intra.csb.ethz.ch/javadoc/metabolic/ch/javasoft/math/NumberOperations.html
You can use negate() function and the BigDecimal constants :)
BigDecimal total = amount.multiply(BigDecimal.ONE.negate());
Related
This question already has answers here:
Fixed Point Arithmetic in C Programming
(4 answers)
Closed 1 year ago.
Suppose a = 3.91900007534.
In C language, I want to store the value of the variable a in another variable, r, up to two decimal places, such that r = 3.92.
Note that I don't want to print the value up to two decimal places, I just want to store the value as I need the exact value of r for the next operation.
Simply, just multiply by 100, truncate the number with floorand divide by 100:
double convert( double in ){
return floor(in*100)/100.0;
}
More generic approach:
#include <math.h>
double convert( double in, int decimals ){
double aux = pow(10,decimals);
return floor(in*aux)/aux;
}
As #Some programmer dude said, the above code truncates. If you wisth to round, just replace floor() by round():
double convert( double in ){
return round(in*100)/100.0;
}
Here the code running: https://onlinegdb.com/By-a1Urf_
The quickest way I can think of doing it is using the following method, ie multiplying by 100, rounding and then dividing again by 100:
int main()
{
float number = 1.2345672;
// Setting precision to 2 digits
number = round(number*100)/100;
printf("%g", number);
return 0;
}
Of course, if you wanted 3 decimal points, it would be 1000, rathern than 100.
So we can make a very good general function, like this:
double precisionSetter(double num, double precision)
{
return round(pow(10,precision)*num)/pow(10,precision);
}
So you can easily choose how many decimal places you want it to:
double a = 1.234567
a = precisionSetter(a,2)
The above will round the float. If you are interested in truncating said float, use the floor() function rather than round() one.
How can I get a float or real value from integer division? For example:
double result = 30/233;
yields zero. I'd like the value with decimal places.
How can I then format so only two decimal places display when used with a string?
You could just add a decimal to either the numerator or the denominator:
double result = 30.0 / 233;
double result = 30 / 233.0;
Typecasting either of the two numbers also works.
As for the second part of the question, if you use printf-style format strings, you can do something like this:
sprintf(str, "result = %.2f", result);
Bascially, the ".2" represents how many digits to output after the decimal point.
If you have an integer (not integer constant):
int i = 20;
int j = 220;
double d = i/(double)j;
This is the simplest way to do what you are trying to achieve, I think..
double result = 30/233.0f;
for iOS development (iPhone/iPad/etc) better to use float type.
float result = 30/233.0f;
How to round result to third digit after the third digit.
float result = cos(number);
Note that I want to save the result up to the third digit, no rounding. And no, I don't want to print it with .3f, I need to save it as new value;
Example:
0.00367 -> 0.003
N.B. No extra zeroes after 3 are wanted.
Also, I need to be able to get the 3rd digit. For example if it is 0.0037212, I want to get the 3 and use it as an int in some calculation.
0.00367 -> 0.003
A float can typically represent about 232 different values exactly. 0.00367 and 0.003 are not in that set.
The closest float to 0.00367 is 0.0036700000055134296417236328125
The closest float to 0.003__ is 0.0030000000260770320892333984375
I want to save the result up to the third digit
This goal needs a compromise. Save the result to a float near a multiple of 0.001.
Scaling by 1000.0, truncating and dividing by 1000.0 will work for most values.
float y1 = truncf(x * 1000.0f) / 1000.0f;
The above gives a slightly wrong answer with some values near x.xxx000... and x.xxx999.... Using higher precision can solve that.
float y2 = (float) (trunc(x * 1000.0) / 1000.0);
I want to get the 3 and use it as an int in some calculation.
Skip the un-scaling part and only keep 1 digit with fmod().
int digit = (int) fmod((trunc(x * 1000.0), 10);
digit = abs(digit);
In the end, I suspect this approach will not completely satisfy OP's unstated "use it as an int in some calculation.". There are many subtitles to FP math, especially when trying to use a binary FP, as are most double, in some sort of decimal way.
Perhaps the following will meet OP's goal, even though it does some rounding.:
int third_digit = (int) lround(cos(number)*1000.0) % 10;
third_digit = abs(third_digit);
You can scale the value up, use trunc to truncate toward zero, then scale down:
float result = trunc(cos(number) * 1000) / 1000;
Note that due to the inexact nature of floating point numbers, the result won't be the exact value.
If you're looking to specifically extract the third decimal digit, you can do that as follows:
int digit = (int)(result * 1000) % 10;
This will scale the number up so that the digit in question is to the left of the decimal point, then extract that digit.
You can subtract from the number it's remainder from division by 0.001:
result -= fmod(result, 0.001);
Demo
Update:
The question is updated with very conflicting requirements. If you have an exact 0.003 number, there will be infinite numbers of zeroes after it, and it is a mathematical property of numbers. OTOH, float representation cannot guarantee that every exact number of 3 decimal digits will be represented exactly. To solve this problem you will need to give up on using the float type and switch to a some sort of fixed point representation.
Overkill, using sprintf()
double /* or float */ val = 0.00385475337;
if (val < 0) exit(EXIT_FAILURE);
if (val >= 1) exit(EXIT_FAILURE);
char tmp[55];
sprintf(tmp, "%.50f", val);
int third_digit = tmp[4] - '0';
What I am saying is that lets say the user inputs a floating point number for ex 4.624.
Then you you have to read this value using scanf and then you might use it to do some sort of calculation by plugging it in a formula or something similar. How can you read that number to two digits after the decimal point which in this case would be 4.62 so that's the number you use in the formula and not the whole number of 4.624.
float x = 4.624;
float x_truncated_to_two_decimal_places = floor(x*100.0) / 100.0;
or
float x_rounded_to_two_decimal_places = round(x*100.0) / 100.0;
depending on what you want.
I am writing a program in C.
Is there any way of determining the number of decimal places
in a float number (i.e. 0.123 = 3, 0.123456 = 6 etc.)?
Other than converting the number to a string and using string
functions to pull the characters after the decimal place?
I have a function named computeFare()
float computeFare()
{
totalFare = (3.40 + basicFare) * (1 + surchargePercent);
return totalFare; // **in this case totalFare = 34.567**
}
printf("Total fare is $%.2f\n",
computeFare());
Result : Total fare is $34.56
I did this and it returned 34.56...
I want it to be $34.57
Thanks,
Lawrence.
Not really, the number of decimal places is a function of the internal representation of the number. What you see when you display the number is, is the number as a string for printing.
So if you are interested in the displayed value, you can control the number of decimal places with formatting directives in the first place e.g., %5.2f, or use the string function approach as you mention in your post after the fact once you have the number as a string.
Also, as an aside, would you count trailing zeros?
Perhaps it would be helpful to state your goal for wanting to do this? There might be other ways to accomplish what you are looking to do.
Update:
Based on your update, the problem is really not counting decimal places, rather you are running into represenation issue/rounding errors (not that uncommon). The problem is that some fractional values can't be exactly represented in base 2. Here's an exhaustive explanation: What Every Computer Scientist Should Know About Floating-Point Arithmetic.
Take a look at this SO question: Understanding floating point representation errors; what's wrong with my thinking?
You can try this approach to round the value:
float rounded_val = floorf(value * 100.0 + 0.5) / 100.0;
Wikipeadia has a whole article on rounding.
The numbers will (in general) be stored in base 2, so fractional numbers are unlikely to correspond precisely to concise decimal strings. In order to get neat decimals, you're probably going to have to round first.
With printf you can specify the amount of decimal places.
%.0f equals no decimal places
%.4f equals float showing four decimal places
A. I wouldn't think so. even if you could get the mantisa (the exponent value) it would be in base 2.
B. Moreover, floating numbers are not accurate so most likely that if you don't have a perfect round number that you have infinite number of decimal places. you wouldn't see them when you print the number cause there are getting cut.
After your latest edit, it sounds like you just want to round, not that you really care about the number of decimal places in a number.
If this is the case you can use code like this:
#include <math.h>
float computeFare()
{
float totalFare;
totalFare = (3.40 + basicFare) * (1 + surchargePercent);
totalFare = floorf(totalFare * 100 + 0.5) / 100; //round the answer
return totalFare; // **in this case totalFare = 34.567**
}
printf("Total fare is $%.2f\n", computeFare());