Ruby: Controlling Printing in Scientific Notation

Ruby: Controlling printing in scientific notation

You can do all sorts of things using the % operator. For example:

x = 123456789012345.to_f
"%f" % x # => "123456789012345.000000"

y = 1.23
"%E" % y # => "1.230000E+000"

The various options are the same as for the sprintf function.

Force Ruby to not output a float in standard form / scientific notation / exponential notation

f.printf "My number: %.5f\n", small_number

You can replace .5 (5 digits to the right of the decimal) with any particular formatting size you like, e.g., %8.3f would be total of 8 digits with three to the right of the decimal, much like C/C++ printf formatting strings.

How to force a Float to display with full precision w/o scientific notation and not as a string?

The string representation and the actual value of a float are two different things.

What you see on screen/print-out is always a string representation, be it in scientific notation or "normal" notation. A float is converted to its string representation by to_s, puts, "%.10f" % and others.

The float value itself is independent of that. So your last sentence does not make much sense. The output is always a string.

To enforce a certain float format in Rails' to_json you can overwrite Float#encode_json, e.g.

class ::Float
def encode_json(opts = nil)
"%.10f" % self
end
end

Put this before your code above. Note that -- depending on your actual values -- you might need more sophisticated logic to produce reasonable strings.

Keep format width in scientific notation

I think you'll have to calculate the digits appropriately.. Something like this, perhaps, will work:

n <- 1234.567e2
prettyNum(n, digits=7-(nchar(n)-11), width=11, format="fg")
# [1] " 123456.7"

n <- 1234.567e9
prettyNum(n, digits=7-(nchar(n)-11), width=11, format="fg")
# [1] "1.23457e+12"

n <- 1234.567e100
prettyNum(n, digits=7-(nchar(n)-11), width=11, format="fg")
# [1] "1.2346e+103"

Or equivalently with format:

format(n, digits=7-(nchar(n)-11), width=11)

Alignment of floating point numbers printed in scientific notation

As Thomas mentioned in the comments, this isn't currently possible only using Rust's formatting parameters. So you'd have to implement your own utility formatting function (or find a crate that offers it).

Here's a quick-n-dirty solution I threw together:

fn fmt_f64(num: f64, width: usize, precision: usize, exp_pad: usize) -> String {
let mut num = format!("{:.precision$e}", num, precision = precision);
// Safe to `unwrap` as `num` is guaranteed to contain `'e'`
let exp = num.split_off(num.find('e').unwrap());

let (sign, exp) = if exp.starts_with("e-") {
('-', &exp[2..])
} else {
('+', &exp[1..])
};
num.push_str(&format!("e{}{:0>pad$}", sign, exp, pad = exp_pad));

format!("{:>width$}", num, width = width)
}
  • width controls the amount of left padded spaces
  • precision is the amount of decimals
  • exp_pad controls the amount of left padded 0s

Example:

fn main() {
let nums = [
0.1111,
0.02222,
3333.0,
-44444.0,
0.0,
1.0,
42.0,
9999999999.00,
999999999999.00,
123456789.1011,
];

for &num in &nums {
println!("{}", fmt_f64(num, 10, 3, 2));
}
}

Output:

 1.111e-01
2.222e-02
3.333e+03
-4.444e+04
0.000e+00
1.000e+00
4.200e+01
1.000e+10
1.000e+12
1.235e+08

why Ruby String each_char method prints an extra % at the end

the program is doing what is expected.

the % is actually the shell prompt.
guessing you do something like:

%my-script.rb
hello world%

because you don't have a new line, when the output finishes the script just takes control back and shows the prompt

Format BigDecimal without scientific notation with full precision

To preserve the precision for a BigDecimal you need to pass the value in as a String

BigDecimal d = new BigDecimal("12334535345456700.12345634534534578901");
System.out.println(d.toPlainString());


Related Topics



Leave a reply



Submit