Is it possible to round an integer value in terraform string interpolations?
It's a bit of a hack and doesn't use terraform string interpolations but..
You can do this with the external data source (https://www.terraform.io/docs/providers/external/data_source.html) by delegating it to another program. The example I've included uses bash and jq. However you could probably achieve this without jq.
Terraform:
data external "rounder" {
program = ["bash", "${path.module}/round.sh"]
query {
value="1.3"
}
}
output "round" {
value = "${data.external.rounder.result.value}"
}
round.sh:
#!/usr/bin/env bash
# Exit if any of the intermediate steps fail
set -e
eval "$(jq -r '#sh "VALUE=\(.value)"')"
ROUNDED=$(printf "%.0f\n" $VALUE)
jq -n --arg rounded "$ROUNDED" '{"value":$rounded}'
Here is an issue about supporting "round" in terraform: https://github.com/hashicorp/terraform/issues/16251
There is another native terraform way of doing this, not sure if it's new but I just found it and thought I should add it here for reference:
format("%.2f", data.aws_ec2_spot_price.emr.spot_price)
This will return my spot_price as a 2 digit number, this uses the width operator in the format function
A width modifier can be included with an optional decimal number immediately preceding the verb letter, to specify how many characters will be used to represent the value. Precision can be specified after the (optional) width with a period (.) followed by a decimal number. If width or precision are omitted then default values are selected based on the given value. For example:
Sequence Result
%f Default width and precision.
%9f Width 9, default precision.
%.2f Default width, precision 2.
%9.2f Width 9, precision 2.
Related
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
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)
I am writing code where I would like the user to enter the desire decimal point precision. For example:
for x in numbers:
print "{:10.*f}".format(x)
...except where the '*' is I would like to place a variable that which the user provided value. My search for a solution in available documentation has proved unfruitful.
How about print '{:10.{precision}f}'.format(x, precision=precision), where precision is a value defined elsewhere?
Python One-liner
number = 10.123456789
print ('{:10.{precision}f}'.format(number, precision=int(input("Enter the precision"))))
Output :
>>> print ('{:10.{precision}f}'.format(number, precision=int(input("Enter the precision\n"))))
Enter the precision
5
10.12346
Where would I insert this in my code? I have a inputs and a message box that I need to get to two decimals but I can't figure out where I should put it.
If you don’t want to print out the String and just want to format it for later use, you can use the static format method of the String class.
It works in exactly the same way as printf as far as formatting is concerned, but it doesn’t print the String, it returns a new formatted String.
String.format "%[argument number] [flags] [width] [.precision] type"
"%" is a special character in formatted String and it denotes start of formatting instruction. String.format() can support multiple formatting instruction with multiple occurrence of "%" character in formatting instruction.
"argument number" is used to specify correct argument in case multiple arguments are available for formatting.
"flags" is another special formatting instruction which is used to print String in some specific format for example you can use flag as "," to print comma on output.
"width" formatting option denotes minimum number or character will be used in output but in case if number is larger than width then full number will be displayed but if its smaller in length then it will be be padded with zero.
"precision" is using for print floating point formatted String, by using precision you can specify till how many decimal a floating point number will be displayed in formatted String.
"type" is the only mandatory formatting option and must always comes last in format String also input String which needs to be formatted must be with same type specified in "type" parameter.
public class StringFromatExample {
public static void main(String[] args) {
String s1 = String.format("%-4.5f %.20f", 35.23429837482,5.2345678901);
System.out.println(s1);
}
}
the output will be
35.23430 5.23456789010000000000
Let's say I had a Perl variable:
my $string = "40.23";
my $convert_to_num = $string * 1;
Is there a way I can find the precision of this float value? My solution so far was to simply just loop through the string, find the first instance of '.', and just start counting how many decimal places, returning 2 in this case. I'm just wondering if there was a more elegant or built-in function for this sort of thing. Thanks!
Here is an answer for "number of things after the period" in $nstring
length(($nstring =~ /\.(.*)/)[0]);
The matching part first finds . (\.), then matches everything else (.*). Since .* is in parentheses, it is returned as the first array element ([0]). Then I count how many with the length() function.
Anything you do in Perl with plain variables will be dependent on the compiler and hardware you use. If you really care about the precision, use
use "Math::BigFloat";
And set the desired properties. The number of digits is more properly termed accuracy in Math::BigFloat.
use Math::BigFloat;
Math::BigFloat->accuracy(12);
$n = new Math::BigFloat "52.12";
print "Accuracy of $n is ", $n->accuracy(), " length ",scalar($n->length()),"\n";
Will return
Accuracy of 52.1200000000 is 12 length 4