Java Nano Second Convert nanosecondsToString(long ns)

Here you can find the source of nanosecondsToString(long ns)

Description

Format a long representing nanoseconds into a string of the form "[seconds].[nanoseconds]" with the appropriate zero-padding.

License

Open Source License

Parameter

Parameter Description
ns the timestamp in nanoseconds

Return

the formatted string

Declaration

public static String nanosecondsToString(long ns) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2009, 2011 Ericsson//from w w  w.j av  a2  s .  c o m
 * 
 * All rights reserved. This program and the accompanying materials are
 * made available under the terms of the Eclipse Public License v1.0 which
 * accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors:
 *   William Bourque - Initial API and implementation
 *   Francois Chouinard - Cleanup and refactoring
 *******************************************************************************/

public class Main {
    /**
     * Format a long representing nanoseconds into a string of the form
     * "[seconds].[nanoseconds]" with the appropriate zero-padding.
     * <p>
     * 
     * @param ns the timestamp in nanoseconds
     * @return the formatted string
     */
    public static String nanosecondsToString(long ns) {
        ns = Math.abs(ns);
        String time = Long.toString(ns);

        int length = time.length();
        if (time.length() > 9) {
            // Just insert the decimal dot
            time = time.substring(0, length - 9) + "." + time.substring(length - 9); //$NON-NLS-1$
            return time;
        }

        // Zero-pad the value
        for (int i = length; i < 9; i++) {
            time = "0" + time; //$NON-NLS-1$
        }
        time = "0." + time; //$NON-NLS-1$
        return time;
    }
}

Related

  1. nano()
  2. nano2milli(double nano)
  3. nanoSeconds(long millis)
  4. nanoSecondsToSeconds(final long nanoSeconds)
  5. nanosecondsToSeconds(Long nanoseconds)
  6. nanoSecondToSecond(double nano, int decimal)
  7. nanoSecToString(final long nS)
  8. nanosForFractionalValue(int value, int width)
  9. nanoTime()