Class: Float

Inherits:
Object
  • Object
show all
Defined in:
lib/gstring.rb

Instance Method Summary collapse

Instance Method Details

#to_eng(pa = 6, unit = nil) ⇒ Object



1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
# File 'lib/gstring.rb', line 1364

def to_eng(pa=6, unit=nil)
  pa = pa.to_i
  pa = (pa<1) ? 1 : (pa>15) ? 15 : pa
  if self < 0.0
    num = -self
    sgn = "-"
  else
    num = self
    sgn = ""  
  end
  str = "%.16e" % num
  str.extract!(1..1)    # remove decimal point
  num = str.parse('e')
  exp = str.to_i
  pos = (exp%3)+1
  if (exp < 0)
    esgn = "-"
    ee  = -(exp/3)*3
  else
    esgn = ""
    ee = (exp/3)*3
  end
  pd = pos > pa ? pos : pa
  num = (num[0..pa].to_f/10).round.to_s[0..(pa-1)].padto(pd,'0',:right)  # round to target size
  num.insert(pos, '.') unless pos >= (num.length)
  pfx = String::SI_UNIT_PREFIXES["#{esgn}#{ee}".to_i]
  unless unit.nil?
    unless pfx.nil?
      num += pfx
      ee=0 # disable 'e' thing
    end
  end
  unit ||= ""  
  if (ee>0)
    num += "e#{esgn}#{ee}"
  end
  return sgn+num+unit
end

#to_numObject



1354
1355
1356
# File 'lib/gstring.rb', line 1354

def to_num
  self
end

#to_scd(dp = 2, delim = ',.') ⇒ Object



1357
1358
1359
1360
1361
1362
1363
# File 'lib/gstring.rb', line 1357

def to_scd(dp=2, delim = ',.')
  num = ((10 ** dp) * self).round.to_s
  man = num[0..(-dp-1)]
  man = man.empty? ? '0' : man
  frt = (num[(-dp)..(-1)] || "").padto(dp,'0',:right)
  return man.reverse.scan(/\d{1,3}/).join(delim.first).reverse + delim.last + frt
end