From 34fd148f2fb4b030fee1ba8c2418be3c75485ce7 Mon Sep 17 00:00:00 2001 From: penguindark <57967770+penguindark@users.noreply.github.com> Date: Wed, 22 Apr 2020 01:42:44 +0200 Subject: [PATCH] ftoa: some fixes for rounding, new functions --- vlib/strconv/ftoa/f32_str.v | 44 ++++++++++++++++++++++++++++++--- vlib/strconv/ftoa/f64_str.v | 49 ++++++++++++++++++++++++++++++++----- 2 files changed, 84 insertions(+), 9 deletions(-) diff --git a/vlib/strconv/ftoa/f32_str.v b/vlib/strconv/ftoa/f32_str.v index 23c7c9bd90..7a09bf525f 100644 --- a/vlib/strconv/ftoa/f32_str.v +++ b/vlib/strconv/ftoa/f32_str.v @@ -65,12 +65,18 @@ const( // max 46 char // -3.40282346638528859811704183484516925440e+38 -fn (d Dec32) get_string_32(neg bool, i_n_digit int) string { +fn (d Dec32) get_string_32(neg bool, i_n_digit int, i_pad_digit int) string { n_digit := i_n_digit + 1 + pad_digit := i_pad_digit + 1 mut out := d.m mut out_len := decimal_len_32(out) out_len_original := out_len + mut fw_zeros := 0 + if pad_digit > out_len { + fw_zeros = pad_digit -out_len + } + mut buf := [byte(0)].repeat(out_len + 5 + 1 +1) // sign + mant_len + . + e + e_sign + exp_len(2) + \0 mut i := 0 @@ -86,7 +92,7 @@ fn (d Dec32) get_string_32(neg bool, i_n_digit int) string { if n_digit < out_len { //println("orig: ${out_len_original}") - out += ten_pow_table_32[out_len - n_digit] + 1 // round to up + out += ten_pow_table_32[out_len - n_digit - 1] * 5 // round to up out /= ten_pow_table_32[out_len - n_digit] out_len = n_digit } @@ -111,6 +117,11 @@ fn (d Dec32) get_string_32(neg bool, i_n_digit int) string { i++ } + for fw_zeros > 0 { + buf[i++] = `0` + fw_zeros-- + } + /* x=0 for x>(mantbits32+expbits32)) != 0 + mant := u & ((u32(1)<> mantbits32) & ((u32(1)< out_len { + fw_zeros = pad_digit - out_len + } + + mut buf := [byte(0)].repeat(out_len + 6 + 1 +1 + fw_zeros) // sign + mant_len + . + e + e_sign + exp_len(2) + \0 mut i := 0 if neg { @@ -96,11 +102,12 @@ fn (d Dec64) get_string_64(neg bool, i_n_digit int) string { disp = 1 } + // rounding last used digit if n_digit < out_len { - //println("orig: ${out_len_original}") - out += ten_pow_table_64[out_len - n_digit] + 1 // round to up - out /= ten_pow_table_64[out_len - n_digit] + out += ten_pow_table_64[out_len - n_digit - 1] * 5 // round to up + out /= ten_pow_table_64[out_len - n_digit ] out_len = n_digit + //println("orig: ${out_len_original} new len: ${out_len}") } y := i + out_len @@ -123,6 +130,11 @@ fn (d Dec64) get_string_64(neg bool, i_n_digit int) string { i++ } + for fw_zeros > 0 { + buf[i++] = `0` + fw_zeros-- + } + /* x=0 for x>(mantbits64+expbits64)) != 0 + mant := u & ((u64(1)<> mantbits64) & ((u64(1)<