Rounding Decimal - decimal

In NSDecimalNumber there's a method to round the number, I.E.
let handler = NSDecimalNumberHandler(roundingMode: .plain, scale: 2, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false)
let example: NSDecimalNumber = 1.345
let rounded: NSDecimalNumber = example.rounding(accordingToBehavior: handler)
Now I've switched to Decimal and it doesn't seem to have the method to round the number like NSDecimalNumber has. Should I cast it to NSDecimalNumber and cast it back to Decimal just to round things up or is there a better and more elegant way of rounding a Decimal?
EDIT: made a better example

Decimal has become an easy and concise way to handle decimal numbers in Swift 3, but if you want to control some rounding mode or rounding scale, you need to use NSDecimal... functions.
Foundation Functions
See Decimals part.
NSDecimalRound(_:_:_:_:)
var dexample: Decimal = 1.345
var drounded: Decimal = Decimal()
NSDecimalRound(&drounded, &dexample, 2, .plain)
print(drounded) //->1.35

It's simple
let x = 1.23556789
let y = Int(round(x))
print(y)

Related

How to get first 4 digits after the 0s in a decimal but keeping 0s • Python

I need the first 4 digits after the front 0s in a decimal while also keeping the 0s in the output without getting scientific notation.
Would like to take
0.0000000000000000000000634546534
and get
0.00000000000000000000006345 but not
6.345e-23.
But would also like to take
231.00942353246
and get
231.009423.
Thank you.
Here's one way using the decimal module.
import decimal
example = 0.0000000000000000000000634546534
x = decimal.Decimal(example)
sign = x.as_tuple().sign
digits = x.as_tuple().digits
exponent = x.as_tuple().exponent
figs = 4
result = decimal.Decimal((sign, digits[:figs], len(digits)+(exponent)-figs))
precision = -1 * (len(digits) + (exponent) - figs) # for this example: -1 * (99 + (-121) - 4)
print("{:.{precision}f}".format(float(result), precision=precision))
Result:
0.00000000000000000000006345
Note that Decimal stores 99 digits because of floating point imprecision. The example variable holds a float value (due to the initializer value) that is inherently imprecise. There is no way around this, unless you are able to represent the original float value as a string, that you can use to initialize the example variable.
There are cases, where the 4th digit shown will be wrong, because in the floating point representation that digit is represented as one lesser and the next digit is a 9, for example. To fix, this, we grab one more digit as well to use for rounding. This should work in most cases, as the imprecision should be within the nearest rounding threshold.
result = decimal.Decimal((0, digits[:figs + 1], len(digits)+(exponent)-figs-1))
Lastly, to handle the case where there are numbers before the decimal, we can simply store it, remove it, and re-add it:
whole_number_part = int(example)
example -= whole_number_part
...
result += whole_number_part
Altogether, we get:
import decimal
example = 231.00942353246
whole_number_part = int(example)
example -= whole_number_part
x = decimal.Decimal(example)
sign = x.as_tuple().sign
digits = x.as_tuple().digits
exponent = x.as_tuple().exponent
figs = 4
result = decimal.Decimal((0, digits[:figs + 1], len(digits)+(exponent)-figs-1))
result += whole_number_part
precision = -1 * (len(digits) + (exponent) - figs)
print("{:.{precision}f}".format(float(result), precision=precision))
Result:
231.009423

simple rounding down decimal places

I wrote a simple function to round down a number based on a certain number of decimal places by using the built-in round function and subtracting the last decimal by 1 if it rounds up.
def rounddown(number, places):
rounded = round(number, places)
if rounded > number:
string = '1'
for x in range(places):
string = string + '0'
return rounded - (1/float(string))
else:
return rounded
my problem is sometimes the results end up being a number like this:
rounddown(4.555756, 5)
4.555750000000001
Could someone explain to me exactly what is going on here? I think it may have something to do with floating point math inaccuracy?
Thank you
The issue is basically Floating point operations ,to avoid the problem
Please use the decimal library as shown below
from decimal import Decimal
def rounddown(number, places):
rounded = round(number, places)
if rounded > number:
string = '1'
for x in range(places):
string = string + '0'
return Decimal(str(rounded))-1/Decimal(string)
else:
return rounded

Representing fractions in MathNet matrices

I am trying solve some matrices calculations using the MathNet.Numericslibraries. It all works fine with double numbers. However now I want to represent numbers as fractions and want to get the answers to the calculations as fractions. How can I do that?
What I am currently doing is this.
var M = Matrix<double>.Build;
var V = Vector<double>.Build;
double [,] x1 = {
{0, 0, 0},
{1.0/2, 0 , 0},
{1.0/2, 1.0, 1.0}
};
var m = M.DenseOfArray(x1);
These fractions gets converted into doubles and the final answer will be in doubles. I want to retain fractions throughout the calculation.
There are no fractions in your code sample. The expression "1.0/2" in C# is not a fraction but another way to write the double literal "0.5d". In fact there is no fraction data type in the .Net framework at all.
The F# extensions of Math.NET Numerics do provide a BigRational type which implements fractions based on BigIntegers, but Math.NET Numerics does not support vectors or matrices of this value type either. Math.NET Symbolics might support this in the future but it's not there yet.

How to force a Float to only have four decimal places

How can I make that a float number only have 4 decimal places at most.
In my J2ME app I have two fields : unitPrice (4 decimal places) and quantity(3 decimal places) and when I multiply them I got number with more decimals than I need:
unitPrice :5.6538
quantity: 5
result: 28.269001
What can I do to have a result of only 4 decimals? and in general what do I need to do to use floats with a specific number of decimals.
Of course, if you were using Java SE the solution would be BigDecimal.
You could round as shown in the result initialization in the following program:
import java.math.BigDecimal;
public class Test {
public static void main(String args[]) {
float unitPrice = 5.6538f;
float quantity = 5;
float rawResult = quantity*unitPrice;
System.out.println(rawResult);
float result = Math.round(10000f*rawResult)/10000f;
System.out.println(result);
System.out.println(new BigDecimal(result));
}
}
The output is:
28.269001
28.269
28.2689990997314453125
Unfortunately, as shown by the final printout using BigDecimal, result is not really exactly 28.269. 28.269 is not exactly representable in any binary fraction format. That could affect future calculations if decimal fractions are really important.
As an alternative, consider doing everything in integers, with each type of data having an associated power-of-ten factor. For unit price, the factor would be 10,000. For quantity, it would be 1000.
For the product, you want it to be 10,000. The intermediate result of doing the multiplication will have a factor of 10^7, so divide by 1000 and round to an integer.
in vb6.0 we can use RonudOff() function for this operation;
example:
unitPrice :5.6538
quantity: 5
result: 28.269001
then " RounOff(result)" will give 28.2690;
i think their may be some similar function in java also
thanks

How to truncate floating point number in jscript?

How to truncate float value in Jscript?
eg.
var x = 9/6
Now x contains a floating point number and it is 1.5.
I want to truncate this and get the value as 1
x = Math.floor(x)
This will round the value of x down to the nearest integer below.
Math.round() should achieve what you're looking for, but of course it'll round 1.5 to 2. If you always want to round down to the nearest integer, use Math.floor():
var x = Math.floor(9 / 6);
Math.floor() only works as the OP intended when the number is positive, as it rounds down and not towards zero. Therefore, for negative numbers, Math.ceil() must be used.
var x = 9/6;
x = (x < 0 ? Math.ceil(x) : Math.floor(x));
Another solution could be:
var x = parseInt(9 / 6);
Wscript.StdOut.WriteLine(x); // returns 1
the main purpose of the parseInt() function is to parse strings to integers. So I guess it might be slower than Math.floor() and methods as such.

Resources