Commit 6f663077

6f663077151fMerged

Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 4 files · +2 added · ~2 modified

Description

Merge pull request #1059 from neidiom/fix/int-ceil-floor-round-truncate-ndigits

runtime,codegen: implement Integer#ceil/floor/round/truncate with ndi…

Details

Commit
6f663077151f
Parent
25031c1dd270
Merge parent
63f9e71a55ca

lib/sp_runtime.hmodifiedView file

@@ -199,6 +199,15 @@
199199 static mrb_int sp_int_sqrt(mrb_int n){if(n<0)return 0;if(n<2)return n;mrb_int x=n,y=(x+1)/2;while(y<x){x=y;y=(x+n/x)/2;}return x;}
200200 static inline char *sp_str_alloc_raw(size_t total_with_null); /* fwd decl */
201201 static const char*sp_int_chr(mrb_int n){char*s=sp_str_alloc_raw(2);s[0]=(char)n;s[1]=0;return s;}
202+/* Integer#round(ndigits): round to nearest 10^(-ndigits).
203+ Integer#ceil(ndigits): round up to 10^(-ndigits).
204+ Integer#floor(ndigits): round down to 10^(-ndigits).
205+ Integer#truncate(ndigits): truncate toward zero at 10^(-ndigits).
206+ Positive ndigits are a no-op on integers. */
207+static mrb_int sp_int_round(mrb_int v,mrb_int nd){if(nd>=0)return v;mrb_int f=(mrb_int)pow(10,-nd);return(mrb_int)round((double)v/f)*f;}
208+static mrb_int sp_int_ceil(mrb_int v,mrb_int nd){if(nd>=0)return v;mrb_int f=(mrb_int)pow(10,-nd);return(mrb_int)ceil((double)v/f)*f;}
209+static mrb_int sp_int_floor(mrb_int v,mrb_int nd){if(nd>=0)return v;mrb_int f=(mrb_int)pow(10,-nd);return(mrb_int)floor((double)v/f)*f;}
210+static mrb_int sp_int_truncate(mrb_int v,mrb_int nd){if(nd>=0)return v;mrb_int f=(mrb_int)pow(10,-nd);return(v>=0?(mrb_int)floor((double)v/f):(mrb_int)ceil((double)v/f))*f;}
202211
203212 /* Forward decls for helpers used across this header (and by the
204213 string->number parsers that now live in libspinel_rt.a). */