How to use Math.round on a big deciaml in groovy? - groovy

I have a variable in my groovy script that collects a cost value. However the value comes out as 91.7776766667 and I want it to be rounded up so it is displayed as 91.8. How can I change the code below to do this and I am struggling to implement the Math.round feature:
def testcost = jsongroups.xxx.cost.flatten().collect { new Math.round(BigDecimal (it)) }
log.info testcost

Instead of Math.round() you can use BigDecimal.setScale(scale, roundingMode) on your number directly.
def testcost = jsongroups.options.cost.flatten().collect { new BigDecimal (it).setScale(1, RoundingMode.HALF_UP)}
log.info testcost
HALF_UP will round .01-.04 to .0 and .05-.09 to .1. Read the JavaDoc of RoundingMode for other rounding possibilities, like HALF_EVEN etc.

Groovy language has a round() method which going to round your decimal number to specific decimal place as a parameter.
def decimalValue = (Double)91.7776766667
println "Value upto two decimal places >>"+decimalValue.round(2)
Output:
Value upto two decimal places >>91.78

Related

Groovy expression to filter strings randomly with specified probability

The input is a random string (not uniformly distributed).
I need a one-liner groovy expression that, based on the input, with specified probability, returns me true or false.
For an input of int value i would use intValue % 100 < p where p is desired probability percentage.
How do I do this for a string? I am thinking of using a hash function, e.g. md5() to make my input more uniform. But the output of string.md5() in groovy is still a string, so what can I do with it?
I thought of comparing last character, e.g. ['0','1'].contains(myString.md5()[31]) but it doesn't allow for decimal granularity and is quite cumbersome to update.
This works just right:
new BigInteger(myString.md5(), 16) % 100 < p

How to convert a String to a Float which is rounded UP to 4 decimal places

I have this string: "123,456.39213212"
I would like to to be converted to a float and rounded UP to the 4th decimal place.
According to an online tool I used I should get this number: 123456.3922
Please advise how I can do this in Groovy?
Thanks
It feels a bit hacky, but if your thousands separator is always , you can do something like this:
import java.math.RoundingMode
def input = "123,456.39213212"
def output = new BigDecimal(input.replaceAll(",", "")).setScale(4, RoundingMode.UP)
​Output:
123456.3922
Key parts are:
Replacing the comma with "" to have the string in a format that BigDecimal can work with and
Setting the scale to 4 using RoundingMode.UP (note: depending on your requirements regarding negative numbers you may want to use RoundingMode.CEILING instead)

Float to Binary and Binary to Float in Python

Can anyone tell me how to convert a float number to 32-bit binary string and from a 32-bit binary string to a float number in python?
'bin' function in python works only for integers.
I need a single bit string as in internal representation. I do not want separate bit strings for the number before and after the decimal places joined by a decimal place in between.
EDIT: The question flagged does not explain how to convert binary string to float back.
Copied from this answer and edited per suggestion from Mark Dickinson:
import struct
def float_to_bin(num):
return format(struct.unpack('!I', struct.pack('!f', num))[0], '032b')
def bin_to_float(binary):
return struct.unpack('!f',struct.pack('!I', int(binary, 2)))[0]
print float_to_bin(3.14) yields “01000000010010001111010111000011”.
print bin_to_float("11000000001011010111000010100100") yields “-2.71000003815”.
I was able to create a program that takes bin decimals as string an returns int decimals!
I used a for loop to start from 1 until the len() of the str+1 to use i number to elevate 2 and, then just keep track of the result with result +=:
def binary_poin_to_number(bin1)->float:
#Try out string slicing here, later
result = 0
for i in range(1,len(bin1)+1):
if bin1[i-1] == '1':
result += 2**-i
return result

How to sum up all numbers in an array

I have an array which outputs the following:
charges = [5.00, 26.00, 8.00, 4.00, 4.00, -8.00, 54.00, 52.48]
When I try to perform a sum using this:
charges.sum()
It gives me:
5.0026.008.004.004.00-8.0054.0052.48
I am assuming I need to convert it from a string to a float so I did:
Float.valueOf((String) charges.sum())
and it gives me an error which states 'multiple points'.
My question is how do I add all of these figures up?
If your list is actually of strings, you can quickly do the conversion with sum()'s closure form.
charges.sum { it.toBigDecimal() }
It is unclear what your list has in it, it seems like the entries in your list are actually strings (since sum concatenates them), or something that prints a string value (has a toString method that returns a string showing the value so you think it is numeric even though it isn’t) . They are definitely not numeric, so convert each of them to a numeric type before summing:
charges.collect { new BigDecimal(it.toString()) }.sum()
(What your code was doing was concatenating the string values together, then converting that to a numeric type.)
You must delete the cast (String)
Float.valueOf(charges.sum())

Cannot return a float value of -1.00

I am currently doing an assignment for a computer science paper at university. I am in my first year.
in one of the questions, if the gender is incorrect the function is suppose to return a value of -1. But in the testing column, it says the expected value is -1.00. And I cannot seem to be able to return the value of '-1.00', it will always return a value of -1.0 (with one zero). I used the .format to make the value 2sf (so it will appear with two zero's) but when converting it to a float the value always returns "-1.0".
return float('{:.2f}'.format(-1))
This isn’t as clear as it could be. Does your instructor or testing
software expect a string '-1.00'? If so, just return that. Is a
float type expected? Then return -1.0; the number of digits shown does
not affect the value.
I don't know exactly what you have done, but i had tried this way and output what you expect.
b = -1
>>> print("%.2f" % (b))
-1.00
>>> print("%.2f" % (-1))
-1.00
What does the following code do?
print(float('{:.2f}'.format(-1)))
The '{:.2f}'.format(-1) creates some string representation of -1. defined by the format string. The float(...) converts this string to the float 1. The print command converts this float to a sting, using some default format, and prints this string to the screen. I think that isn't what you expected because the format you used does not effect the print command in formatting the string.
I assume you want
print('{:.2f}'.format(float(-1)))
and this actually does what you want, it prints
1.00
http://ideone.com/GyINQR
It is not necessary to convert -1 explicitely to float
print('{:.2f}'.format(-1))
gives the desired result:
http://ideone.com/U2RTMX

Resources